# 1.selenium手动登录并获取cookie from selenium import webdriver from selenium.webdriver.common.by import By from selenium.common.exceptions import NoSuchElementException import time import json driver = webdriver.Chrome() driver.get("https://passport.bilibili.com/login") flag = True print("等待登录...") while flag: try: driver.find_element(By.XPATH, "//div[@class='user-con signin']|//ul[@class='right-entry']" "//a[@class='header-entry-avatar']") flag = False except NoSuchElementException as e: time.sleep(3) print("已登录,现在为您保存cookie...") with open('cookie.txt', 'w', encoding='u8') as f: json.dump(driver.get_cookies(), f) driver.close() print("cookie保存完成,游览器已自动退出...") # 2.那么后续selenium程序启动时如何直接使用该cookie而不需再次登录呢? driver = webdriver.Chrome() with open('cookie.txt', 'r', encoding='u8') as f: cookies = json.load(f) driver.get("https://www.bilibili.com/") for cookie in cookies: driver.add_cookie(cookie) driver.get("https://www.bilibili.com/") # 上面的流程就是先访问要加载cookie的网站,再迅速向其添加cookie,再重新访问一遍该网站加载的cookie即可生效
手动和自动获取cookie方式
最新推荐文章于 2024-04-11 11:02:57 发布