Python Selenium等待不起作用/Java Selenium问题



我遇到了一个问题,就我的一生而言,我不明白为什么它不起作用,尤其是因为使用应该非常简单。我根本无法等待在Selenium中工作。隐性和显性的等待根本不起作用,我也不知道为什么。

这是我的代码:

from os import times
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.common.by import By
import json
from dataclasses import dataclass, asdict
import time
USER_NAME = "username"
PASSWORD = "password"

options = webdriver.ChromeOptions()
options.add_argument('--igcognito')
#options.add_argument('--headless')
driver = webdriver.Chrome('c:\path\to\chromedriver.exe',options=options)

driver.get("URL")

driver.find_element_by_name("username").send_keys(USER_NAME)
driver.find_element_by_name("password").send_keys(PASSWORD)
driver.find_element_by_xpath("/html/body/div/div/div/div[2]/div[2]/form/button").click()
driver.get("URL")
driver.implicitly_wait(30)

expansion_buttons = driver.find_elements_by_class_name("class-control")
print(len(expansion_buttons))
for x in range(len(expansion_buttons)):
driver.execute_script("arguments[0].click();", expansion_buttons[x])
#time.sleep(120)
#driver.implicitly_wait(60)
try:
wait = WebDriverWait(driver, 120)
wait.until(expected_conditions.visibility_of_all_elements_located((By.CLASS_NAME, "stuff")))
finally:
# driver.quit()
pass
vehicles_classes = driver.find_elements_by_class_name("stuff")
print(len(vehicles_classes))

1尽量不要混合隐式和显式等待。它可能导致不可预测的等待期。查看此处了解更多信息

2如果选择使用严格隐式等待,则在开始时声明它。像这样:

from os import times
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.common.by import By
import json
from dataclasses import dataclass, asdict
import time
USER_NAME = "username"
PASSWORD = "password"
options = webdriver.ChromeOptions()
options.add_argument('--igcognito')
#options.add_argument('--headless')
driver = webdriver.Chrome('c:\path\to\chromedriver.exe',options=options)
driver.implicitly_wait(30)  # Declare here!    
driver.get("URL")

driver.find_element_by_name("username").send_keys(USER_NAME)
driver.find_element_by_name("password").send_keys(PASSWORD)

3您明确的等待:

wait = WebDriverWait(driver, 120)
wait.until(expected_conditions.visibility_of_all_elements_located((By.CLASS_NAME, "stuff")))

它看起来是正确的,但是不清楚您为什么在这里使用try/finally。除非有确切的原因,否则在等待的情况下你并不真正需要它。120-太长。减少等待时间。

4driver.find_element_by_xpath("/html/body/div/div/div/div[2]/div[2]/form/button").click()似乎是一个非常不稳定的XPath。我建议您学习XPathcss选择器。如果使用单个元素,则它们应该是唯一的。

5我强烈建议只使用显式等待。请在此处查看如何正确使用它们https://selenium-python.readthedocs.io/waits.html#explicit-等待

总体建议:从小处着手。打开一个站点,然后逐步检查每个操作。不要试图一下子把所有事情都自动化。对于初学者来说,这将是非常困难的。

最新更新