1 from selenium import webdriver 2 3 driver = webdriver.PhantomJS(executable_path='G:/OpenSources/phantomjs-2.1.1-windows/bin/phantomjs') 4 driver.get("http://pythonscraping.com") 5 driver.implicitly_wait(1) 6 print(driver.get_cookies()) 7 8 savedCookies = driver.get_cookies()10 11 driver2 = webdriver.PhantomJS(executable_path='G:/OpenSources/phantomjs-2.1.1-windows/bin/phantomjs') 12 driver2.get("http://pythonscraping.com") 13 driver2.delete_all_cookies() 14 for cookie in savedCookies: 15 driver2.add_cookie(cookie) 16 17 driver2.get("http://pythonscraping.com") 18 driver2.implicitly_wait(1) 19 print(driver2.get_cookies())
以上代码15行报错: "errorMessage":"Can only set Cookies for the current domain"
将15行代码改为:
1 driver2.add_cookie({k: cookie[k] for k in ('name', 'value', 'domain', 'path', 'expiry') if k in cookie})
修改后报错: "errorMessage":"Unable to set Cookie"
最终修改:
1 from selenium import webdriver 2 import time 3 4 driver = webdriver.PhantomJS(executable_path='G:/OpenSources/phantomjs-2.1.1-windows/bin/phantomjs') 5 driver.get("http://pythonscraping.com") 6 driver.implicitly_wait(1) 7 print(driver.get_cookies()) 8 9 savedCookies = driver.get_cookies()11 12 driver2 = webdriver.PhantomJS(executable_path='G:/OpenSources/phantomjs-2.1.1-windows/bin/phantomjs') 13 driver2.get("http://pythonscraping.com") 14 driver2.delete_all_cookies() 15 for cookie in savedCookies: 16 # fix the problem-> "errorMessage":"Unable to set Cookie" 17 for k in ('name', 'value', 'domain', 'path', 'expiry'): 18 if k not in list(cookie.keys()): 19 if k == 'expiry': 20 t = time.time() 21 cookie[k] = int(t) # 时间戳 秒 22 # fix the problem-> "errorMessage":"Can only set Cookies for the current domain" 23 driver2.add_cookie({k: cookie[k] for k in ('name', 'value', 'domain', 'path', 'expiry') if k in cookie}) 24 25 driver2.get("http://pythonscraping.com") 26 driver2.implicitly_wait(1) 27 print(driver2.get_cookies())
在这个例子中,第一个 webdriver获得了一个网站,打印 cookie 并把它们保存到变量savedCookies里。第二个webdriver加载同一个网站(技术提示:必须首先加载网站,这样Selenium 才能知道cookie 属于哪个网站,即使加载网站的行为对我们没任何用处),删除所有的cookie ,然后替换成第一个webdriver得到的cookie 。当再次加载这个页面时,两组cookie 的时间戳、源代码和其他信息应该完全一致。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构