python - 使用 Selenium Python 客户端在不同浏览器中处理 headless (headless)模式

标签 python selenium headless google-chrome-headless firefox-headless

我目前正在开发一个使用 Selenium 的 Python (3.7) CLI 程序,它将被不同的人群使用。
我遇到的问题如下:
用于在 中设置“ headless (headless)”等选项 Chrome 我用

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--headless")
driver = webdriver.Chrome(executable_path,options=chrome_options)
对于 火狐 ,代码如下所示:
from selenium import webdriver
from selenium.webdriver.firefox.options import Options

options = Options()
options.headless = True
driver = webdriver.Firefox(executable_path,options=options)
所以我想知道是否有办法规范这些设置/优雅地处理不同的浏览器,或者我是否必须基本上编写所有内容 2 甚至 3 次(可能添加 Safari 或 Opera)?

最佳答案

根据 Selenium 的变更日志Python 客户端 v3.12.0:

  • Deprecate Options set_headless methods in favor of property setter

因此,如果您使用的是 Selenium WebDriver v 3.12.0 或更高版本,而不是 chrome_options.add_argument("--headless")您需要使用 headless 属性 setter 如下:
options.headless = True
否则您可能会看到 DeprecationWarning如下:
DeprecationWarning: use setter for headless property instead of set_headless opts.set_headless(headless=True)

You can find a relevant detailed discussion in DeprecationWarning: use setter for headless property instead of set_headless opts.set_headless(headless=True) using Geckodriver and Selenium in Python



引用
几个相关的讨论:
  • How to make firefox headless programmatically in Selenium with python?
  • How to configure ChromeDriver to initiate Chrome browser in Headless mode through Selenium?
  • 关于python - 使用 Selenium Python 客户端在不同浏览器中处理 headless (headless)模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63262476/

    相关文章:

    python - 如何用selenium同时打开多个chrome配置文件?

    python - 如何使 Python Structlog 在不使用关键字 `event` 的情况下进行记录

    selenium - 使用脚本设置 Selenium 网格

    ruby - 如何以编程方式获取 selenium、selenium 服务器或 selenium webdriver 的运行版本?

    python - pandas 中的数据争论

    python - 多项式回归图上的多条轨迹

    java - 如何在java中检查元素中的字符串是否为 "valid date formate"、 "today"或 "yesterday"

    content-management-system - headless (headless)/解耦 CMS 建议

    java - 为什么 headless (headless) NetLogo 模拟在高端计算机集群上的运行速度比在台式机上慢?

    javascript - 使用 phantomjs 在单击时加载 javascript/ajax 调用