对于我正在使用的html element,有两种可能的xpath配置。
我想检查第一个配置是否存在,时间不超过1秒。然后,我想检查是否存在第二个配置。我就是这样做的:
import time
from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import TimeoutException
browser.get(URL)
browser.implicitly_wait(6)
element = browser.find_elements_by_xpath("/html/body/div[4]/div[3]/div[1]/ ......")
try:
time1 = time.time()
# The following 2 lines are taking too long:
wait = WebDriverWait(element, 1)
finalElement1 = wait.until(EC.presence_of_element_located((By.XPATH, ".//div[@class='classNAME']/a/header/div[@class='OtherClassName']/span[@class='FinalClassName']"))).text
print("First element took (seconds) to find :" + str((time.time()-time1)))
# This prints around 0.02 seconds
except (TimeoutException, Exception):
print("Took this amount of seconds to timeout: "+ str((time.time()-time1)))
# This prints around 6 seconds
try:
time1 = time.time()
tempElement = element.find_element_by_xpath(".//div[@class='_0xLoFW _78xIQ- EJ4MLB JT3_zV']/a/header/div[@class='_0xLoFW u9KIT8 _7ckuOK']")
finalElement1 = tempElement.find_element_by_xpath(".//span[@class='u-6V88 ka2E9k uMhVZi dgII7d z-oVg8 _88STHx cMfkVL']").text
finalElement2 = tempElement.find_element_by_xpath(".//span[@class='u-6V88 ka2E9k uMhVZi FxZV-M z-oVg8 weHhRC ZiDB59']").text
print("Second element took (seconds) to find : "+ str((time.time()-time1)))
# This prints around 0.08 seconds
except:
print("None of the above")
continue
pass主要问题是当我显式地将finalElement1设置为wait = WebDriverWait(element, 1)时,查找它的函数(在第一个try块中)需要大约6秒的时间超时。我很困惑
我知道已经有很多关于就这样和在selenium博客上的内容,但由于某些原因,我无法让它发挥作用。有人知道为什么会这样吗?
发布于 2020-11-06 05:57:19
答案可以在正式文档中找到,打开这个url并查看以下内容:
警告:不要混合隐式和显式等待。这样做会导致不可预测的等待时间。例如,设置10秒的隐式等待和15秒的显式等待可能导致20秒后发生超时。
如果您确实需要同时使用隐式和显式等待,您可以尝试如下:
browser.implicitly_wait(0) <-- set implicit wait to the default value 0 before explicit waits
finalElement1 = wait.until(EC.presence_of_element_located((By.XPATH, ".//div[@class='classNAME']/a/header/div[@class='OtherClassName']/span[@class='FinalClassName']"))).text
browser.implicitly_wait(6) <-- set implicit wait to the value you need after explicit waitshttps://stackoverflow.com/questions/64668848
复制相似问题