python - 将 --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:消息:
解决方案
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")
添加自定义用户代理,因为无头浏览器使用无头作为用户代理,某些网站的行为会有所不同
推荐阅读
- python - Keras 模型未训练
- python - 如何在金字塔python中打印字符串
- google-cloud-platform - 日志条目 API 未检索日志条目
- python - TypeError:不支持的操作数类型 -:'int' 和 'NoneType' python3
- javascript - Laravel ConsoleTvs 通过 Javascript 附加图表->容器
- python - 通过 python 编辑 powerpoint .pptx 模板
- html - 在“V”形内将 CSS 中的文本居中
- python - python电报机器人发件人过滤器
- sql - 如何在 ORM 中转换此 SQL?
- mysql - 如何最好地在 MYSQL 中存储和索引多个整数的所有唯一组合?