Python+Selenium 跳过Cookies,登录网站

前提

1.账号可以不用每次都登录,下次可以直接跳过登录的步骤

实现过程

1.先登录一次,保证Cookies是可以跳过登录的最新Cookies。
2.复制Cookies文件和Local State文件
3.复制到别的文件夹
4.使用chrome浏览器的Options参数指定你复制到的文件夹
5.再打开浏览器就可以登录成功

代码实现

import re
import os
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from webdriver_manager.chrome import ChromeDriverManager

class GrabBoard:

    # 对cookie文件进行处理
    def del_file(self,path):
        for i in os.listdir(path):
            path_file = os.path.join(path, i)
            if os.path.isfile(path_file):
                os.remove(path_file)
            else:
                self.del_file(path_file)

    # 执行浏览器启动功能
    def createocstask(self):
        surl = "https://www.baidu.com"

        # 地址路径
        delete_path = "D:\\AT Tool\\0.Software\\4.RunFast\\googlecook"
        self.del_file(delete_path)
        GooglePath = os.path.expanduser('~') + r'\AppData\Local\Google\Chrome\User Data'
        GooglecookPath = r'D:\AT Tool\0.Software\4.RunFast\googlecook\User Data'

        # 循环文件,保证文件正确
        for root, dirs, names in os.walk(GooglePath):
            for fname in names:
                if 'Cookies' == fname:
                    CookSrcPath = os.path.join(root, fname)
                elif "Local State" == fname:
                    LocalStateSrcPath = os.path.join(root, fname)

        CookTargetPath = GooglecookPath + re.search("User Data(.*)", CookSrcPath, re.M | re.I).group(0).replace("User Data",
                                                                                                                "").replace(
            "Cookies", "")
        LocalStateTargetPath = GooglecookPath + re.search("User Data(.*)", LocalStateSrcPath, re.M | re.I).group(0).replace(
            "User Data", "").replace(
            "Local State", "")

        # 调用系统xcopy功能
        os.system('xcopy "%s" "%s" /y' % (CookSrcPath, CookTargetPath))
        os.system('xcopy "%s" "%s" /y' % (LocalStateSrcPath, LocalStateTargetPath))

        # chrome浏览器的Options参数
        opt = Options()
        # 指定用户文件夹User Data路径,可以把书签这样的用户数据保存在系统分区以外的分区。
        opt.add_argument(r'--user-data-dir=D:\AT Tool\0.Software\4.RunFast\googlecook\User Data')  # havepath
        opt.add_argument('--no-sandbox')# 解决DevToolsActivePort文件不存在的报错
        opt.add_argument('--disable-dev-shm-usage')


        self.browser = webdriver.Chrome(ChromeDriverManager().install() ,chrome_options=opt)

        #pyinstaller -F Reminder_card.py

        # 打开url地址网页

        self.browser.get(surl)
       	self.browser.implicitly_wait(10)


grabboard = GrabBoard()
grabboard.createocstask()

版权声明:本文为aa122509969原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。