这是代码:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.options import DesiredCapabilities
PATH='C:\Coding_projects\chromedriver.exe'
options = Options()
driver=webdriver.Chrome(PATH,options=options)
def open_ouedkniss():
options.add_argument('headless')
driver.get("https://www.ouedkniss.com/")
ad_button=driver.find_element_by_id('header_interstitiel_exit')
ad_button.click()
search_bar=driver.find_element_by_id('menu_recherche_query')
search_bar.click()
search_bar.send_keys('golf 6')
search_bar.send_keys(Keys.RETURN)
open_ouedkniss()
当我运行代码时,一切正常,但即使使用无头选项,浏览器窗口仍然打开,有人可以告诉我为什么吗?
尝试替换代码中的这一行
options.add_argument('headless')
与
options.add_argument('--headless')
还要在
options = Options()
代码之后写上上面的行。
根据您的问题,您似乎正在尝试使用搜索选项在网页中搜索特定术语。我认为您没有必要使用
RETURN
键来按 RETURN
除非您想专门测试此功能。
使用 Selenium 4 RC-1 候选(您可以使用
pip install selenium==4.0.0.rc1
安装它),我能够通过这段代码实现这一目标 -
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
options = Options()
options.add_argument('--headless')
svc=Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=svc,options=options)
driver.set_window_size(1400,900)
driver.get("https://www.ouedkniss.com/")
wait = WebDriverWait(driver,30)
wait.until(EC.visibility_of_element_located((By.ID,'menu_recherche_query')))
search_bar = driver.find_element(By.ID,'menu_recherche_query')
search_bar.click()
search_bar.send_keys('golf 6')
search_button = driver.find_element(By.ID,'menu_recherche_submit')
search_button.click()
driver.save_screenshot('headfull.png')
driver.quit()