python - 在 headless Chrome 中等待包含元素的网页时出现超时异常

标签 python selenium selenium-webdriver selenium-chromedriver

以下代码使用非 headless Chrome 并且可以工作:

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)

当我选择使用 headless chrome 时:

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: 

因此,在 headless 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。为什么会这样?

最佳答案

我过去所做的是添加参数“--start-maximized”:

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

尝试一下希望对你有帮助!

关于python - 在 headless Chrome 中等待包含元素的网页时出现超时异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56682149/

相关文章:

python - Django 自定义模型字段 : to_python() not called

python - 删除 Django DB 中的重复行

python - Selenium在完成所有功能后单独关闭浏览器

selenium - 如何从警告框中获取文本

java - 无法使用java处理firefox上selenium webdriver中的警报

python - PyTorch:检查模型准确性导致 "TypeError: ' bool' 对象不可迭代。”

python - 压缩大量相似的字符串

selenium - Appium - 验证标签的值没有改变

perl - Selenium::Remote::Driver 或 WWW::Selenium

python - 删除由 selenium/chromedriver 传递给 chrome 的参数