Chrome Headless选项不工作selenium python

vshtjzan  于 2023-09-28  发布在  Go
关注(0)|答案(3)|浏览(125)

代码如下:

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()

当我运行代码时,一切正常,但即使使用headless选项,浏览器窗口仍然打开,有人能告诉我为什么吗?

vdgimpew

vdgimpew1#

尝试在代码中替换此行
options.add_argument('headless')

options.add_argument('--headless')
options = Options()代码后面也写上一行。

o2gm4chl

o2gm4chl2#

根据您的问题,看起来您正在尝试使用搜索选项在网页中搜索特定术语。我不认为你有必要使用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()
gupuwyp2

gupuwyp23#

你最好使用--headless=new,因为--headless根据Headless is Going Away!使用旧的无头模式:

options.add_argument('--headless=new')

相关问题