4

I'm having trouble enabling cookies with headless chrome in Selenium. I thought they were supposed to be enabled by default, but when navigating to: https://www.whatismybrowser.com/detect/are-cookies-enabled, it says they are not enabled. Since that, I've tried adding preferences to enable them explicitly, but still get the same result. I've also tried using undetected-chromedriver instead of chromedriver, but both produce the same result. I'm kind of lost here, and can't find anything else online, so I'd appreciate any guidance. Below is the code in python that I am using.

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()
asoingbob
  • 41
  • 2

0 Answers0