Selenium操作领英登录Cookie保存正常加载时报InvalidCookieDomain错误如何解决
问题根本原因
触发InvalidCookieDomainException错误的核心原因是:Selenium的add_cookie接口要求,注入Cookie前浏览器必须已经访问过Cookie对应域名的站点。你的原有逻辑在driver初始化完成后直接加载Cookie,此时浏览器默认停留的空白页域名与领英域名不匹配,所有Cookie都无法被正常注入,即便加了try-except跳过报错也无法实现免密登录。
额外存在的小问题:
- 跳过二次验证提示的XPath存在语法错误,
contains(text(),'Skip'缺少右括号 find_elements返回的是元素列表,不能直接调用click方法
修复方案
- 加载Cookie前先导航到领英域名下的任意页面(建议先访问
https://www.linkedin.com/404这类加载速度快的页面,避免跳转登录页) - 完成Cookie注入后刷新页面,触发领英的登录态校验
- 修复原有XPath的语法错误
修正后的完整代码
import time import traceback import pickle from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.common.exceptions import NoSuchElementException class Browser: def __init__(self,username,password): chrome_options = Options() prefs = { "download_restrictions": 3, } chrome_options.add_experimental_option( "prefs", prefs ) # 可根据需要添加无头模式等其他配置 # chrome_options.add_argument("--headless") driver = webdriver.Chrome('chromedriver',options=chrome_options) self.driver=driver self.username=username self.password=password self.login() def login(self): # 先访问领英域名站点,为注入Cookie做准备 self.driver.get("https://www.linkedin.com/404") try: print("trying to load cookie if available") self.loadcookie() # 注入完成后跳转到首页验证登录态 self.driver.get("https://www.linkedin.com/feed/") # 简单校验:当前地址不包含login字段则说明Cookie登录成功 if "login" not in self.driver.current_url: print("cookie登录成功") return except Exception: print("some problem with cookie or its not available") traceback.print_exc() # Cookie失效则走账号密码登录流程 self.driver.get("https://www.linkedin.com/login") self.driver.find_element_by_id('username').send_keys(self.username) self.driver.find_element_by_id('password').send_keys(self.password) self.driver.find_element_by_id('password').send_keys("\n") try: # 修复XPath语法错误和元素调用错误 self.driver.find_element_by_xpath("//*[contains(text(),'Skip')]").click() except NoSuchElementException: pass self.savecookies() def loadcookie(self): print("loading cookie") cookies = pickle.load(open("cookies.pkl", "rb")) for cookie in cookies: # 可选过滤:自动跳过已过期的Cookie if 'expiry' in cookie and cookie['expiry'] < time.time(): continue self.driver.add_cookie(cookie) def savecookies(self): print("saving cookie") time.sleep(10) pickle.dump( self.driver.get_cookies() , open("cookies.pkl","wb"))
内容的提问来源于stack exchange,提问作者Nikhil Singh
相关产品推荐
相关产品推荐

