如何在 Python 中使用 Selenium 运行无头 Microsoft Edge?

May*_*her 7 python selenium-webdriver microsoft-edge microsoft-edge-headless browser-options

使用 Chrome,您可以在创建驱动程序时添加选项。你只要做

options = Options()
options.headless = True
driver = webdriver.Chrome(PATH\TO\DRIVER, options=options)
Run Code Online (Sandbox Code Playgroud)

但由于某种原因,当尝试对 Microsoft Edge 执行相同操作时

options = Options()
options.headless = True
driver = webdriver.Edge(PATH\TO\DRIVER, options=options)
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

TypeError: init () 得到了意外的关键字参数 'options'

由于某种原因,Edge 的驱动程序不接受除文件路径之外的任何其他参数。有没有办法像 Chrome 一样运行 Edge 无头并添加更多选项?

PDH*_*ide 7

  options = EdgeOptions()
  options.use_chromium = True
  options.add_argument("headless")
  options.add_argument("disable-gpu")
Run Code Online (Sandbox Code Playgroud)

尝试上面的代码,你必须启用 chromium 才能启用 headless

https://learn.microsoft.com/en-us/microsoft-edge/webdriver-chromium/?tabs=python

这仅适用于新的 Edge Chromium,不适用于 Edge 旧版本。在旧版本中不支持无头

完整代码

from msedge.selenium_tools import EdgeOptions
from msedge.selenium_tools import Edge

# make Edge headless
edge_options = EdgeOptions()
edge_options.use_chromium = True  # if we miss this line, we can't make Edge headless
# A little different from Chrome cause we don't need two lines before 'headless' and 'disable-gpu'
edge_options.add_argument('headless')
edge_options.add_argument('disable-gpu')
driver = Edge(executable_path='youredgedriverpath', options=edge_options)
Run Code Online (Sandbox Code Playgroud)

  • 我得到`AttributeError:'Options'对象没有属性'AddArgument'` (2认同)