1

我无法在 Selenium 中启用带有无头 chrome 的 cookie。我认为它们应该默认启用,但是当导航到:https://www.whatismybrowser.com/detect/are-cookies-enabled时,它说它们没有启用。从那以后,我尝试添加首选项以明确启用它们,但仍然得到相同的结果。我也尝试过使用 undetected-chromedriver 而不是 chromedriver,但两者都产生相同的结果。我有点迷路了,在网上找不到其他任何东西,所以我很感激任何指导。下面是我正在使用的python中的代码。

import selenium
from selenium.webdriver.chrome.options import Options
import undetected_chromedriver as uc
from fake_useragent import UserAgent

#Creating Random User Agent
ua = UserAgent()
userAgent = ua.random

#Chrome Options
chrome_options = uc.ChromeOptions()
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--headless')
chrome_options.add_argument('window-size=1920,1080')
chrome_options.add_argument("--enable-javascript")
chrome_options.add_argument(f'user-agent={userAgent}')

#Trying to set preferences for cookies (Found this from the following stackoverflow post: https://stackoverflow.com/questions/48667852/how-to-change-allow-sites-to-save-and-read-cookie-data-recommended-and-or-bloc/67260066#67260066)
prefs = {"profile.default_content_setting_values.cookies": 1, "profile.cookie_controls_mode": 0}
chrome_options.add_experimental_option("prefs", prefs)

#Initializes driver
driver = uc.Chrome(options=chrome_options)

#Navigates to website to check if cookies enabled
driver.get("https://www.whatismybrowser.com/detect/are-cookies-enabled")

#Prints true if cookies enabled and false if disabled
print(driver.find_element_by_id("detected_value").text=="Yes")
driver.close()
4

0 回答 0