以下代码使用无头镀铬,并且可以正常工作:

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


chrome_options = Options()
chrome_options.add_argument("--headless")
chrome_options.add_argument('--start-maximized')
chrome_options.binary_location = 'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe'

driver = webdriver.Chrome(executable_path=os.path.abspath("C:\User\Program Files\chrome-driver\chromedriver.exe"))

driver.set_window_size(1200, 600)

driver.get("login-url")
driver.find_element_by_id("loginId").send_keys("uname")
driver.find_element_by_id("newPassword").send_keys("pwd")
driver.find_element_by_name("submit-button").click()
driver.set_window_size(1200, 800)
WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.ID,"user-info")))

v = driver.find_element_by_xpath("//tr[4]/td[5]/span").text

print(v)


当我选择使用无头镀铬时:

driver = webdriver.Chrome(executable_path=os.path.abspath("C:\User\Program Files\chrome-driver\chromedriver.exe"), chrome_options=chrome_options)


它引发以下异常:

Traceback (most recent call last):
  File "C:/User/workspaces/pyworkspaces/fin2/venv/process.py", line 28, in <module>
    WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.ID,"user-info")))
  File "C:\User\workspaces\pyworkspaces\fin2\venv\lib\site-packages\selenium\webdriver\support\wait.py", line 80, in until
    raise TimeoutException(message, screen, stacktrace)
selenium.common.exceptions.TimeoutException: Message:


因此,在无头镀铬中,以下行似乎失败了:

WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.ID,"user-info")))


我也尝试了presence_of_element_located

WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID,"user-info")))


但是它仍然给出TimeOutException。为什么会这样呢?

最佳答案

我过去所做的就是添加参数'--start-maximized':

chrome_options.add_argument('--start-maximized')


尝试一下,希望对您有所帮助!

08-26 02:21