首页 > 解决方案 > 如何在 Selenium Chrome 上禁用 Cookie?

问题描述

我一直在寻找stackoverflow,但找不到解决方案。我确实找到的解决方案显然已经过时了。

chrome_options = webdriver.ChromeOptions()
chrome_options.add_experimental_option("prefs", {"profile.default_content_settings.cookies": 2})

driver = webdriver.Chrome(chrome_options=chrome_options)

这是我得到的错误

Traceback (most recent call last):
  File "C:\Users\amete\Documents\Python\Code\Web test.py", line 10, in <module>
    driver = webdriver.Chrome(chrome_options=chrome_options)
  File "C:\Users\amete\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 73, in __init__
    self.service.start()
  File "C:\Users\amete\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\common\service.py", line 81, in start
    raise WebDriverException(
selenium.common.exceptions.WebDriverException: Message: 'chromedriver' executable needs to be in PATH. Please see https://sites.google.com/a/chromium.org/chromedriver/home


Process finished with exit code 1

我的代码:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
PATH = r"C:\Users\amete\Documents\chromedriver.exe"
driver = webdriver.Chrome(PATH)

chrome_options = webdriver.ChromeOptions()
chrome_options.add_experimental_option("prefs", {"profile.default_content_settings.cookies": 2})

driver = webdriver.Chrome(chrome_options=chrome_options)

driver.get("https://www.google.com/")
print (driver.title)

search = driver.find_element_by_id("input")
search.send_keys("One Piece")
search.send_keys(Keys.RETURN)

time.sleep(5)
driver.quit()

标签: pythonselenium

解决方案


一切看起来都很好,但是错误说 chromedriver' executable needs to be in PATH,对吧?

这意味着而不是:

driver = webdriver.Chrome(chrome_options=chrome_options)

你需要这样做:

driver = webdriver.Chrome(executable_path = PATH, chrome_options=chrome_options)

应该为你工作。


推荐阅读