首页 > 解决方案 > Python,selenium - 如何在不显示浏览器窗口的情况下运行脚本

问题描述

如何在不显示浏览器的情况下运行 selenium 代码(代码运行但浏览器窗口不会显示)?

标签: pythonseleniumselenium-chromedriverheadless

解决方案


您可以使用无头模式,它运行 Selenium 脚本而不显示浏览器。

要运行 chrome-headless,只需添加 --headless via chrome_options.add_argument,如下所示:

from selenium import webdriver 
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
#chrome_options.add_argument("--disable-extensions")
#chrome_options.add_argument("--disable-gpu")
#chrome_options.add_argument("--no-sandbox") # linux only
chrome_options.add_argument("--headless")
chrome_options.add_argument("--start-maximized");
# chrome_options.headless = True # also works
driver = webdriver.Chrome(options=chrome_options)

推荐阅读