簡體   English   中英

Selenium WebDriverWait 花費的時間太長

[英]Selenium WebDriverWait is taking too long

我正在使用的 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

主要問題是,當我將它顯式設置為wait = WebDriverWait(element, 1)時,查找finalElement1 (在第一個 try 塊中)的函數需要大約 6 秒才能超時。 我糊塗了

我知道在 SOselenium 博客已經有很多關於此的內容,但由於某種原因我無法讓它工作。 有誰知道它為什么會這樣?

答案可以在官方文檔中找到,打開這個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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM