Selenium WebDriverWait花费的时间太长

时间:2020-11-03 18:53:08

标签: python selenium

我正在使用的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)时,寻找DialogServiceEx(在第一个try块中)的函数超时大约需要6秒钟。我很困惑

我知道关于on SOon the selenium blog的内容已经很多,但是由于某些原因,我无法使其正常工作。有谁知道为什么它会这样?

1 个答案:

答案 0 :(得分:0)

答案可以在官方文档中找到,打开this 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 waits