使用Selenium向新闻网站提交评论提示Cookie被阻止如何解决
这个错误本质是目标站点识别到Selenium启动的浏览器为自动化爬虫环境,故意触发Cookie校验失败报错,和真实的Cookie开关无关,手动使用普通Chrome环境没有自动化特征,所以能正常提交,可通过以下方法修复:
修复方案
1. 添加浏览器启动参数,消除自动化特征,允许Cookie存储
修改后的完整代码如下:
from selenium import webdriver from selenium.webdriver.chrome.options import Options import time chrome_options = Options() # 消除Selenium自动化标识 chrome_options.add_argument("--disable-blink-features=AutomationControlled") chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"]) chrome_options.add_experimental_option("useAutomationExtension", False) # 显式允许Cookie存储 chrome_options.add_argument("--enable-cookies") chrome_options.add_experimental_option("prefs", { "profile.default_content_setting_values.cookies": 1, "profile.cookie_controls_mode": 0 }) driver = webdriver.Chrome(options=chrome_options) # 覆盖浏览器webdriver属性,进一步隐藏自动化特征 driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", { "source": """ Object.defineProperty(navigator, 'webdriver', { get: () => undefined }) """ }) url = "https://www.delfi.lt/en/lifestyle/earth-day-events-for-the-spring-equinox.d?id=87005127" driver.get(url) # 点击Cookie同意后增加等待,确保Cookie写入完成 cookies_ok = '//*[@id="c-right"]/a' driver.find_element_by_xpath(cookies_ok).click() time.sleep(2) # 后续原有操作不变 anon = '//*[@id="comments-listing"]/div[2]/div/div[2]/div/ul/li[1]/span' name = '//*[@id="inputDiv"]/div/form/input' comment = '//*[@id="inputDiv"]/div/form/div[3]/div/textarea' button = '//*[@id="inputDiv"]/div/form/div[4]/div[2]/button[1]' driver.find_element_by_xpath(anon).click() driver.find_element_by_xpath(name).send_keys('name') driver.find_element_by_xpath(comment).send_keys('comment') driver.find_element_by_xpath(button).click()
2. 兜底方案:使用本地Chrome持久化配置
如果上述方法仍不生效,可在启动参数中添加一行配置,直接调用你平时手动使用的Chrome用户配置,环境和手动操作完全一致:
chrome_options.add_argument("user-data-dir=替换为你本地Chrome用户目录的实际路径")
- Windows系统默认路径为
C:\\Users\\你的用户名\\AppData\\Local\\Google\\Chrome\\User Data - Mac系统默认路径为
~/Library/Application Support/Google/Chrome - Linux系统默认路径为
~/.config/google-chrome
内容的提问来源于stack exchange,提问作者denisafonin
相关产品推荐
相关产品推荐

