等待网页带有无头Chrome中的元素的超时异常

时间:2019-06-20 08:39:39

标签: python selenium selenium-webdriver selenium-chromedriver

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

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: 

因此,它似乎在以下行中使用了无头的chrome失败:

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。为什么会这样?

2 个答案:

答案 0 :(得分:0)

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

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

尝试它希望对您有帮助!

答案 1 :(得分:0)

您无需等待{strong> presence_of_element_located() 即可使用Locator Strategy,而无需使用visibility_of_element_located()

  • 使用ID

    element = WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.ID,"user-info")))
    
  • 使用CSS_SELECTOR

    element = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "#user-info")))
    
  • 使用XPATH

    element = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//*[@id='user-info']")))
    
  • 注意:您必须添加以下导入:

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