selenium 跳过登录使用cookie登录网站!

研究了一下怎么使用cookie登录网站,代码写的很乱,功能已实现,算是自己记录一下。

以下是登录扣扣的例子。

from seleniumbase import BaseCase
import json
import pickle
from time import sleep
class GetCookie(BaseCase):
    def save_cookies(self, i):
        cookies_dict = {}
        cookies = self.driver.get_cookies()
        for cookie in cookies:
            cookies_dict[cookie['name']] = cookie['value']
        with open("cookies.txt" + str(i), 'w+') as file:
            json.dump(cookies_dict, file)

    def get_cookies(self):
        with open('qq.txt', 'r') as file:
            cookies = json.load(file)
        # print(cookies)
        return cookies

    def test_login(self):
        tbCookies = self.get_cookies()  # 调用get_cookie方法读取已经获取的cookie

        self.driver.get("https://mail.qq.com/cgi-bin/loginpage")
        for cookie in tbCookies:
            self.driver.add_cookie({
                "domain": ".mail.qq.com",
                "name": cookie,
                "value": tbCookies[cookie],
                "path": '/',
                "expires": None
            })
        self.driver.get("https://mail.qq.com/cgi-bin/loginpage")
        sleep(10)

    # 获取cookie
    def stest_getcookie(self):
        url2 = "https://mail.qq.com/cgi-bin/loginpage"
        self.open(url2)
        sleep(5)
        try:
            self.click("#img_out")
        except:
            print("没有快捷登录,请手动扫码")
            sleep(10)

        for i in range(5):
            sleep(2)
            self.save_cookies(i)
            sleep(20)
            self.driver.refresh()
            self.save_cookies(i)

你可能感兴趣的:(python,测试)