python - Selenium 没有获取 cookie

标签 python selenium selenium-webdriver

我正在尝试使用显式配置文件保存 cookie。代码如下:

browser_profile = webdriver.FirefoxProfile()
browser_profile.set_preference("browser.privatebrowsing.autostart", True)
browser_profile.set_preference("general.useragent.override", "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:62.0) Gecko/20100101 Firefox/62.0")
driver = webdriver.Firefox(firefox_profile=browser_profile)
driver.get("https://google.com")
result = driver.get_cookies()
# result= []

如果我简化代码(或者使用预定的配置文件),我将得到结果:

driver = webdriver.Firefox()
driver.get("https://google.com")
result = driver.get_cookies()
# result= [{'name': 'CONSENT', 'value': 'WP.272dd2', 'path': '/', 'domain': '.google.com', 'expiry': 2145916800, 'secure': False, 'httpOnly': False}, {'name': 'NID', 'value': '144=DdGwYa-bPLiDsp-IPfZdRdkjsQXMzLeex53S9nmb3uzp687exfmO_Z8Hq2bDgEQu58Kq16MX7wI0UhHx6S1y_vJU9z8GYylKy4kBEmQE8e6EJnupEClBy_ZbEPFsBklbsPzkG-tS3RfqzIy-COjamlZHiQJFp0YLlegUWMlzq1k', 'path': '/', 'domain': '.google.com', 'expiry': 1556392000, 'secure': False, 'httpOnly': True}, {'name': '1P_JAR', 'value': '2018-10-26-19', 'path': '/', 'domain': '.google.com', 'expiry': 1543172801, 'secure': False, 'httpOnly': False}]

但是,这样我就无法设置我想要的确切参数。我想知道为什么以及如何解决这个问题。有想法吗?我错过了什么吗?

最佳答案

这是由于此首选项设置。当我以 false 条件运行时,它返回 cookie。

browser_profile.set_preference("browser.privatebrowsing.autostart", True)

看起来 privatebrowsing 会阻止 cookie 跟踪抛出 webdriver。但是当我尝试通过隐私浏览方式通过 javascript 执行器时,我得到了 cookie。

print(driver.execute_script("return document.cookie"))

关于python - Selenium 没有获取 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53014954/

相关文章:

javascript - 如何调整 chromeOptions 缩放级别而不用担心需要传入此 id?

python - Selenium 实现 Try except 并写入 JSON

python - 下载 HTML5 cache.manifest 文件中列出的所有工件的最佳方式?

maven - 在 Maven Cucumber 报告中构建失败时不会生成报告

python - 在 music21 中创建音符图像

python - Tkinter 在 Selenium 进程中卡住

python - 使用 python selenium 将 adblocker 扩展与 headless chrome 驱动程序结合使用

python - 我的脚本无法解析复杂网页中的项目

python - render_template 和重定向之间的区别?

python - web.py 和 gunicorn