Skip to main content
 首页 » 编程设计

python之Selenium 没有得到 cookies

2024年12月31日1098°冷暖

我正在尝试使用显式配置文件保存 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}] 

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

请您参考如下方法:

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

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

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

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