python selenium新增cookie自動登入
阿新 • • 發佈:2021-08-06
1. 先用selenium手動登入,儲存cookie。
import time import json from selenium import webdriver options = webdriver.ChromeOptions() options.add_argument('--disable-gpu') # 禁用gpu options.add_argument("--start-maximized") # 視窗最大 options.add_argument('--ignore-certificate-errors') #忽略一些莫名的問題 # options.add_argument('--proxy-server={0}'.format(proxy.proxy)) # 加代理options.add_experimental_option('excludeSwitches', ['enable-automation']) # 開啟開發者模式 options.add_argument('--disable-blink-features=AutomationControlled') # 谷歌88版以上防止被檢測 # options.add_argument('--headless') # 無介面 driver = webdriver.Chrome(options=options) # 將chromedriver放到Python安裝目錄Scripts資料夾下 driver.get('http://www.****login') # 此處手動輸入賬號密碼登入網站 time.sleep(100) cookies = driver.get_cookies() with open('cookies_180.json', 'w') as f: f.write(json.dumps(cookies))
2. selenium攜帶cookie自動登入。
import json from selenium import webdriver options = webdriver.ChromeOptions() options.add_argument('--disable-gpu') #禁用gpu options.add_argument("--start-maximized") # 視窗最大 options.add_argument('--ignore-certificate-errors') # 忽略一些莫名的問題 # options.add_argument('--proxy-server={0}'.format(proxy.proxy)) # 加代理 options.add_experimental_option('excludeSwitches', ['enable-automation']) # 開啟開發者模式 options.add_argument('--disable-blink-features=AutomationControlled') # 谷歌88版以上防止被檢測 # options.add_argument('--headless') # 無介面 driver = webdriver.Chrome(options=options) # 將chromedriver放到Python安裝目錄Scripts資料夾下 driver.get('http://***.cn') # 此處不要再放登入的網址,可以用未登入的首頁 driver.delete_all_cookies() # 刪除所有cookie資訊 with open('cookies.json', 'r', encoding='utf-8') as f: cookie_list = json.loads(f.read()) for cookie in cookie_list: driver.add_cookie(cookie) driver.refresh() # 到此處selenium已經自動登入了