首页 > 解决方案 > 将 --headless 添加到 chrome 驱动程序后,Selenium 停止工作

问题描述

我正在通过 Selenium 创建一个自动化机器人,并且我曾经使用普通驱动程序构建以查看发生了什么。

该机器人与普通驱动程序完美配合,但现在我想让它不可见,但问题出现了。我阅读了如何实现它并在这里检查了类似的问题,但找不到解决方案..

这是工作代码:

from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as Expected
from selenium.webdriver.common.by import By

driver = webdriver.Chrome("*the path to the driver*")

URL = "https://www.twitter.com/"
driver.get(URL)
press = WebDriverWait(driver, 10).until(
        Expected.element_to_be_clickable((By.CSS_SELECTOR, "button[class='default']"))).click()

这是我添加无头的方法

from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as Expected
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options

options = Options()
options.add_argument("--headless")
driver = webdriver.Chrome("*the path to the driver*", options = options)

URL = "https://www.twitter.com/"
driver.get(URL)
press = WebDriverWait(driver, 10).until(
        Expected.element_to_be_clickable((By.CSS_SELECTOR, "button[class='default']"))).click()

没有无头选项,它工作得很好,但有了它,我在这一行得到错误:

press = WebDriverWait(driver, 10).until(

错误是:“.../webdriver/support/wait.py”,第 37 行,直到引发 TimeoutException(消息,屏幕,堆栈跟踪)selenium.common.exceptions.TimeoutException:消息:

标签: pythonselenium

解决方案


options.add_experimental_option(
    "excludeSwitches", ['enable-automation'])

options.add_argument(
    "user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36")
options.add_argument("--remote-debugging-port=9222")

添加自定义用户代理,因为无头浏览器使用无头作为用户代理,某些网站的行为会有所不同


推荐阅读