如何通过Selenium配置ChromeDriver以在无界面模式下启动Chrome浏览器?

131
我正在编写一个Python脚本进行网页抓取,并使用Chromedriver作为其中的一个包。我希望这可以在没有任何弹出窗口的情况下在后台运行。我正在使用Chromedriver上的“headless”选项,它似乎在不显示浏览器窗口方面做得很好,但是我仍然看到.exe文件正在运行。请参见我所说的内容的截图:截图 这是我用来启动ChromeDriver的代码:
options = webdriver.ChromeOptions()
options.add_experimental_option("excludeSwitches",["ignore-certificate-errors"])
options.add_argument('headless')
options.add_argument('window-size=0x0')
chrome_driver_path = "C:\Python27\Scripts\chromedriver.exe"

我尝试过在选项中将窗口大小更改为0x0,但我不确定是否有任何作用,因为.exe文件仍然弹出。

你有任何想法吗?

我使用的是Python 2.7,供您参考。


可能是使用无头Chrome Webdriver运行Selenium的重复问题。 - Basj
9
这个问题比您链接的那个问题早一年。如果有什么区别,那么被链接的问题可能是这个问题的重复。 - Allan Lago
2
我知道回答一个四年前的问题是个坏主意,但我看到没有人真正解决被显示的问题。如果平台是Windows,你可以这样做:import win32guiimport win32.lib.win32con as win32con,在代码中包含类似 Hwnd = win32gui.FindWindowEx(None,None,None,chrome_driver_path) 的内容,然后 win32gui.ShowWindow(Hwnd,win32con.SW_HIDE),稍后如果你想再次显示它,你需要 win32gui.ShowWindow(Hwnd,win32con.SW_SHOW)。该代码将完全隐藏窗口,只能通过后台运行的任务管理器等程序查看。 - Pear
18个回答

200

它应该看起来像这样:

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

options = Options()
options.add_argument('--headless')
options.add_argument('--disable-gpu')  # Last I checked this was necessary.
driver = webdriver.Chrome(CHROMEDRIVER_PATH, chrome_options=options)

这对我来说使用Python 3.6是有效的,我相信它也适用于2.7。

更新2018-10-26:现在你可以直接这样做:

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

options = Options()
options.headless = True
driver = webdriver.Chrome(CHROMEDRIVER_PATH, options=options)

更新于2023-05-22: Chrome的无头模式得到了升级,现在无头和有头模式已经统一在同一实现下。请参阅https://developer.chrome.com/articles/new-headless/

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

options = Options()
options.add_argument('--headless=new')
driver = webdriver.Chrome(CHROMEDRIVER_PATH, options=options)

要尝试新的无头模式,请传递 --headless=new 命令行标记:

chrome --headless=new

目前,旧版无头模式仍然可通过以下方式使用:

chrome --headless=old

目前,如果在命令行上使用--headless标志而没有显式提供值,则仍会激活旧的无头模式,但我们计划随着时间的推移将其默认更改为新的无头模式。


谢谢!不幸的是,这并没有解决问题。但我已经发布了我的答案。感谢你的帮助。 - Maz
14
将以下代码中的: options = Options() 替换为 options = webdriver.ChromeOptions() 即可应用最新的更新。请注意,翻译过程中不得更改原始信息的含义,并尽可能使翻译通俗易懂。 - TomKivy
更新:Chrome 的 kwarg chrome_options 已被弃用,建议使用 options - gavin
解决方案在网站有 JavaScript 时无法正常工作。我添加了 options.add_argument('user-agent=fake-useragent'),然后它就可以工作了。 - jaycode
options.add_argument('--disable-gpu') 不是必需的。 - undefined

97

2018年10月13日答案更新

现在,您可以通过使用Selenium驱动的ChromeDriver来初始化一个浏览上下文,只需通过Options()类的实例将--headless属性设置为true即可,如下所示:

  • Effective code block:

    from selenium import webdriver
    from selenium.webdriver.chrome.options import Options
    
    options = Options()
    options.headless = True
    driver = webdriver.Chrome(options=options, executable_path=r'C:\path\to\chromedriver.exe')
    driver.get("http://google.com/")
    print ("Headless Chrome Initialized")
    driver.quit()
    

2018年4月23日答案更新

以编程方式在下调用现在变得更加容易,因为可以使用以下方法set_headless(headless=True)

  • Documentation :

    set_headless(headless=True)
        Sets the headless argument
    
        Args:
            headless: boolean value indicating to set the headless option
    
  • Sample Code :

    from selenium import webdriver
    from selenium.webdriver.chrome.options import Options
    
    options = Options()
    options.set_headless(headless=True)
    driver = webdriver.Chrome(options=options, executable_path=r'C:\path\to\chromedriver.exe')
    driver.get("http://google.com/")
    print ("Headless Chrome Initialized")
    driver.quit()
    

注意--disable-gpu 参数已在内部实现。


2018年3月30日的原始回答

在使用无头模式下的Selenium客户端3.11.xChromeDriver v2.38Google Chrome v65.0.3325.181时,您需要考虑以下几点:

  • You need to add the argument --headless to invoke Chrome in headless mode.

  • For Windows OS systems you need to add the argument --disable-gpu

  • As per Headless: make --disable-gpu flag unnecessary --disable-gpu flag is not required on Linux Systems and MacOS.

  • As per SwiftShader fails an assert on Windows in headless mode --disable-gpu flag will become unnecessary on Windows Systems too.

  • Argument start-maximized is required for a maximized Viewport.

  • Here is the link to details about Viewport.

  • You may require to add the argument --no-sandbox to bypass the OS security model.

  • Effective code block :

    from selenium import webdriver
    from selenium.webdriver.chrome.options import Options
    
    options = Options()
    options.add_argument("--headless") # Runs Chrome in headless mode.
    options.add_argument('--no-sandbox') # Bypass OS security model
    options.add_argument('--disable-gpu')  # applicable to windows os only
    options.add_argument('start-maximized') # 
    options.add_argument('disable-infobars')
    options.add_argument("--disable-extensions")
    driver = webdriver.Chrome(chrome_options=options, executable_path=r'C:\path\to\chromedriver.exe')
    driver.get("http://google.com/")
    print ("Headless Chrome Initialized on Windows OS")
    
  • Effective code block :

    from selenium import webdriver
    from selenium.webdriver.chrome.options import Options
    
    options = Options()
    options.add_argument("--headless") # Runs Chrome in headless mode.
    options.add_argument('--no-sandbox') # # Bypass OS security model
    options.add_argument('start-maximized')
    options.add_argument('disable-infobars')
    options.add_argument("--disable-extensions")
    driver = webdriver.Chrome(chrome_options=options, executable_path='/path/to/chromedriver')
    driver.get("http://google.com/")
    print ("Headless Chrome Initialized on Linux OS")
    

通过YouTube视频的步骤

如何通过Selenium在最大化模式下初始化Chrome浏览器

结尾

如何在Python中使用Selenium编程地使Firefox无头运行?


简述

这是沙盒故事的链接。


2
这里需要再进行一次编辑,使用 chrome_options=options 而不是 options=options - Jortega
2
另一个: 使用 options.add_argument("--headless") 而不是 options.headless = True - Jortega
@DebanjanB,当我使用您于2018年10月13日提供的代码时,它可以执行,但会抛出以下错误:“解析元素内容时出错:';'不是有效的键值对分隔符。请改用','。”“脚本只能关闭由其打开的窗口。”以及“在主线程上同步进行的XMLHttpRequest已过时,因为它对最终用户的体验产生了负面影响...”针对网站https://test.plexonline.com - 使用“head”的浏览器没有错误...有什么想法吗? - Programming_Learner_DK
@Python_Learner_DK 完整的错误堆栈跟踪可能会给我们一些线索。您能否提出一个新问题,并附上您的二进制版本? - undetected Selenium
@DebanjanB,这是一个新问题:https://stackoverflow.com/questions/60058246/going-headless-in-selenium-with-chrome-using-python-executing-but-throwing-erro - Programming_Learner_DK
1
@Jortega,chrome_options已经被弃用了,所以正确的写法是options=options。 - Rene

33

2020年8月20日更新(仍然有效)- 现在更简单了!

chrome_options = webdriver.ChromeOptions()
chrome_options.headless = True

self.driver = webdriver.Chrome(
            executable_path=DRIVER_PATH, chrome_options=chrome_options)

16

更新 在我的情况下它运行良好:

from selenium import webdriver

options = webdriver.ChromeOptions()
options.headless = True
driver = webdriver.Chrome(CHROMEDRIVER_PATH, options=options)

在2020年进行了修改。对我而言运作良好。


10
所以在我更正代码后,它变成了:
options = webdriver.ChromeOptions()
options.add_experimental_option("excludeSwitches",["ignore-certificate-errors"])
options.add_argument('--disable-gpu')
options.add_argument('--headless')
chrome_driver_path = "C:\Python27\Scripts\chromedriver.exe"

运行脚本时,.exe文件仍会出现。尽管如此,它确实消除了一些额外的输出,告诉我“无法启动GPU进程”。
最终有效的方法是使用.bat文件运行Python脚本
所以基本上,
1.将Python脚本保存在一个文件夹中 2.打开文本编辑器,并转储以下代码(当然要编辑您的脚本) c:\ python27 \ python.exe c:\ SampleFolder \ ThisIsMyScript.py%* 3.保存.txt文件并将扩展名更改为.bat 4.双击运行该文件
这样只是在命令提示符中打开了脚本,而ChromeDriver似乎在此窗口内操作,而不会弹出到我的屏幕前面,从而解决了问题。

6
  1. 根据谷歌的说法,“在无界面或没有显示服务器依赖的情况下,运行 .exe 程序。”

  2. 建议在命令行参数前加上两个破折号,即 options.add_argument('--headless')

  3. 在无头模式下,还建议禁用 GPU,即 options.add_argument('--disable-gpu')


4

尝试使用ChromeDriverManager

from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager 
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.set_headless()
browser =webdriver.Chrome(ChromeDriverManager().install(),chrome_options=chrome_options)
browser.get('https://google.com')
# capture the screen
browser.get_screenshot_as_file("capture.png")

3

我曾经在pexels.com上工作,并且恰好遇到了这种情况。这个方案非常有效。 - Syed Muntazir Mehdi

1
System.setProperty("webdriver.chrome.driver",
         "D:\\Lib\\chrome_driver_latest\\chromedriver_win32\\chromedriver.exe");
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("--allow-running-insecure-content");
chromeOptions.addArguments("--window-size=1920x1080");
chromeOptions.addArguments("--disable-gpu"); 
chromeOptions.setHeadless(true);
ChromeDriver driver = new ChromeDriver(chromeOptions);

1
起初,我在使用Selenium的无头模式时遇到了一个问题——Chrome浏览器显示空白屏幕。我试图覆盖用户代理,但没有帮助。然后我在文档中看到,针对Chrome 109及更高版本,建议以下面的方式设置无头模式:
options.addArguments("--headless=new")

https://www.selenium.dev/selenium/docs/api/java/org/openqa/selenium/chromium/ChromiumOptions.html#setHeadless(boolean)

因此,启动无头模式的完整代码如下:

ChromeOptions options = new ChromeOptions()
options.addArguments("--window-size=1920,1080")
options.addArguments("--headless=new") 
options.setExperimentalOption("w3c", false) 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接