如何配置ChromeDriver通过Selenium以无头模式启动Chrome浏览器?

如何配置ChromeDriver通过Selenium以无头模式启动Chrome浏览器?

问题描述:

我正在使用python脚本进行网络抓取,并且没有使用Chromedriver作为软件包之一.我希望此操作无需任何弹出窗口即可在后台运行.我在chromedriver上使用了无头"选项,它似乎在不显示浏览器窗口的情况下完成了工作,但是,我仍然看到.exe文件正在运行.查看我在说什么的屏幕截图. 屏幕截图

I'm working on a python script to web-scrape and have gone down the path of using Chromedriver as one of the packages. I would like this to operate in the background without any pop-up windows. I'm using the option 'headless' on chromedriver and it seems to do the job in terms of not showing the browser window, however, I still see the .exe file running. See the screenshot of what I'm talking about. Screenshot

这是我用来启动ChromeDriver的代码:

This is the code I am using to initiate 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文件仍然弹出,因此我不确定这样做是什么.

Things I've tried to do is alter the window size in the options to 0x0 but I'm not sure that did anything as the .exe file still popped up.

关于如何做到这一点的任何想法?

Any ideas of how I can do this?

我正在使用Python 2.7 FYI

I am using Python 2.7 FYI

因此,将我的代码更正为:

So after correcting my code to:

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进程".

The .exe file still came up when running the script. Although this did get rid of some extra output telling me "Failed to launch GPU process".

最终的工作是使用.bat文件运行我的Python脚本

What ended up working is running my Python script using a .bat file

基本上,

  1. 如果有文件夹则保存python脚本
  2. 打开文本编辑器,并转储以下代码(请编辑为您的脚本)

  1. Save python script if a folder
  2. Open text editor, and dump the following code (edit to your script of course)

c:\ python27 \ python.exe c:\ SampleFolder \ ThisIsMyScript.py%*

c:\python27\python.exe c:\SampleFolder\ThisIsMyScript.py %*

保存.txt文件并将扩展名更改为.bat

Save the .txt file and change the extension to .bat

因此,这只是在命令提示符中打开了脚本,ChromeDriver似乎可以在此窗口中运行,而不会弹出到屏幕的前面,从而解决了问题.

So this just opened the script in Command Prompt and ChromeDriver seems to be operating within this window without popping out to the front of my screen and thus solving the problem.