如何在不显示打开的页面的情况下使用带有 chromedriver 和 python 的 selenium 获取页面源代码?

How can I get the page source, without showing the page opened, using selenium with chromedriver and python?

我在 Chrome 驱动程序中使用 selenium;如何在不显示打开的页面的情况下获取页面源?我应该在 webdriver.ChromeOptions() 中指定什么? 这里的代码:

from selenium.common.exceptions import WebDriverException
from selenium.webdriver.chrome.options import Options

chrome_options = Options()
chrome_options.add_argument("???")
bowser = webdriver.Chrome(chrome_options=chrome_options)


browser = webdriver.Chrome() 
try:
    browser.get("www.google.com")
    html_content = browser.page_source
    #do stuff
    browser.quit()
except WebDriverException:
    print "Invalid URL"

你不应该使用 ChromeDriver,而是一些像 HtmlUnitDriver 这样的无头 Webdriver,解释说 here

如果您坚持使用 selenium,那么您可以使用任何无头浏览器,例如 htmlunit 驱动程序。 否则,您可以只在 URL 上发送获取请求并获取响应文本。