有没有办法在不显示浏览器的情况下使用 selenium webdriver?

Is there a way to use a selenium webdriver without showing the browser?

我试着在这个网站上搜索解决方案,因为有一个问题和我的几乎一样。遗憾的是,这对我不起作用。下面的代码是我现在所拥有的......是否可以在不实际显示过程的情况下启动 webdriver?

# Options
options = Options()
options.add_argument('--headless')
options.add_argument('--disable-gpu')


# Gegevens
password = input("Please give us a password you want to use for all your account(s): ")


# Start de driver
url = 'https://twitter.com/?lang=en-gb'
driver = webdriver.Chrome('/Users/ducov/Downloads/chromedriver')
driver = webdriver.Chrome(chrome_options=options)
driver.set_window_size(1600, 800)
driver.get(url)

编辑: 我通过替换为答案中的代码来修复它:

driver = webdriver.Chrome('/Users/ducov/Downloads/chromedriver')
driver = webdriver.Chrome(chrome_options=options)

我仍然收到错误消息:

C:/Users/ducov/PycharmProjects/bot/app.py:18: DeprecationWarning: use options instead of chrome_options
  driver = webdriver.Chrome('/Users/ducov/Downloads/chromedriver', chrome_options=options)

但我认为这不重要

你应该把 execute_pathchrome_options 放在同一行。

driver = webdriver.Chrome('/Users/ducov/Downloads/chromedriver', chrome_options=options)

ps: 在你的代码中,你 运行 2 Chrome 个实例,一个是 webdriver.Chrome('/Users/ducov/Downloads/chromedriver'),另一个是 webdriver.Chrome(chrome_options=options)

你已经足够接近了。

首先,chrome_options 现已弃用,您必须改用 options

  • Implementation:

    if chrome_options:
        warnings.warn('use options instead of chrome_options', DeprecationWarning)
        options = chrome_options
    

其次,您只想初始化单个 Chrome 浏览上下文,因此您需要在单个 [= 中传递两个参数33=]Driver / Chrome初始化如下:

# Options
chrome_options = Options()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')

# Gegevens
password = input("Please give us a password you want to use for all your account(s): ")

# Start de driver
url = 'https://twitter.com/?lang=en-gb'
driver = webdriver.Chrome(executable_path='/Users/ducov/Downloads/chromedriver', options=chrome_options)
driver.set_window_size(1600, 800)
driver.get(url)