如果您在 Python 中使用 Selenium Web 驱动程序,则可以使用 PyVirtualDisplay,它是 Xvfb 和 Xephyr 的 Python 包装器。
PyVirtualDisplay 需要 Xvfb 作为依赖项。在Ubuntu,先安装Xvfb:
sudo apt-get install xvfb
然后从PyPI安装PyVirtualDisplay:
pip install pyvirtualdisplay
使用 PyVirtualDisplay 以无头模式在 Python 中使用 Selenium 脚本示例:
#!/usr/bin/env python
from pyvirtualdisplay import Display
from selenium import webdriver
display = Display(visible=0, size=(800, 600))
display.start()
# Now Firefox will run in a virtual display.
# You will not see the browser.
browser = webdriver.Firefox()
browser.get('http://www.google.com')
print browser.title
browser.quit()
display.stop()
编辑
最初的答案是在 2014 年发布的,现在我们正处于 2018 年的风口浪尖。与其他一切一样,浏览器也在进步。 Chrome 现在有一个完全无头的版本,无需使用任何第三方库来隐藏 UI 窗口。示例代码如下:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
CHROME_PATH = '/usr/bin/google-chrome'
CHROMEDRIVER_PATH = '/usr/bin/chromedriver'
WINDOW_SIZE = "1920,1080"
chrome_options = Options()
chrome_options.add_argument("--headless")
chrome_options.add_argument("--window-size=%s" % WINDOW_SIZE)
chrome_options.binary_location = CHROME_PATH
driver = webdriver.Chrome(executable_path=CHROMEDRIVER_PATH,
chrome_options=chrome_options
)
driver.get("https://www.google.com")
driver.get_screenshot_as_file("capture.png")
driver.close()