如何在无头模式下将以下代码调整为 运行?

How can I adapt the following code to run in headless mode?

我正在使用以下代码:

import time
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium import webdriver

PATH= r"C:\Users\Hamid\Desktop\Selenium\chromedriver.exe"

driver=webdriver.Chrome(PATH)
driver.get("https://www.google.com/")
click_button=driver.find_element_by_xpath('//*[@id="L2AGLb"]/div').click()
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.NAME, "q"))).send_keys("ONS data")
search=driver.find_element_by_xpath('/html/body/div[1]/div[3]/form/div[1]/div[1]/div[3]/center/input[1]').click()

我如何调整它以使其在无头模式下运行?

您似乎在使用 Selenium v3.x。因此,要使用无头模式,您只需通过 Options()class如下:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

options = Options()
options.headless = True
PATH= r"C:\Users\Hamid\Desktop\Selenium\chromedriver.exe"
driver=webdriver.Chrome(executable_path=PATH, options=options)
driver.get("https://www.google.com/")
click_button=driver.find_element_by_xpath('//*[@id="L2AGLb"]/div').click()
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.NAME, "q"))).send_keys("ONS data")