首页 > 解决方案 > Selenium Python 如何使用现有浏览器的 cookie 进行登录验证

问题描述

我有一个已经登录到网站的浏览器(不是由 selenium 生成的)。

我需要 selenium 使用现有的 cookie,以免提示每个生成的浏览器进行新的登录。

这是我已经从我搜索的内容中尝试过但仍然无法使其工作的内容。

代码总结:如果 selenium 生成的浏览器已经登录,浏览器会关闭,如果重定向到登录页面,会等待 60 秒再关闭。

import selenium.webdriver.support.ui as ui
import contextlib
import getpass

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options


websiteURL = "https://website.alreadylogged.in"
currentUser = getpass.getuser()

chromeOptions = Options()
chromeOptions.add_argument("--user-data-dir=C:\\Users\\" + currentUser + "\\AppData\\Local\\Google\\Chrome\\User Data\\Default")
driver = webdriver.Chrome(executable_path="C:\\Users\\"+currentUser+"\\Documents\\chromedriver.exe",options=chromeOptions)

with contextlib.closing(driver) as chromeDriver:    
    chromeOptions.add_argument("user-data-dir=C:\\Users\\" + currentUser + "\\AppData\\Local\\Google\\Chrome\\User Data\\Default") 
    chromeDriver.get(websiteURL)
    wait = ui.WebDriverWait(chromeDriver, 60) # timeout after 60 seconds
    wait.until(lambda driver: chromeDriver.find_elements_by_class_name('      windows chrome      '))

标签: pythonseleniumcookies

解决方案


推荐阅读