Selenium-Python - 如何减少NoSuchElementException的时间

时间:2018-04-27 20:09:55

标签: python selenium selenium-webdriver webdriver nosuchelementexception

我有一个测试用例,我需要检查点击一个元素时,不显示弹出窗口。这段代码工作正常,但是对于NoSuchElementException,它需要太长时间,60秒,打印PASS条件并转到下一个测试用例。在这种情况下,如何减少等待时间?

driver.find_element_by_xpath(
".//*[@id='assetIdDIV']/div/myaots-input/div/div/div[1]/span/i[2]"
).click()

try:
    DUP_popup = driver.find_element_by_xpath(
    ".//*[@id='DuplicateTicketsPopup']/div/div/div/div[1]/span[2]/img"
    )

    if (DUP_popup):
        print ("Duplicate tkts popup is displayed - Fail")

except NoSuchElementException:
        print ("Duplicate popup not displayed - PASS")

3 个答案:

答案 0 :(得分:1)

您可以使用显式等待。

  

默认情况下,WebDriverWait每500次调用一次ExpectedCondition   毫秒,直到它在超时内成功返回,   否则抛出TimeoutException

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

try:
  DUP_popup = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.XPath, 
      "//*[@id='DuplicateTicketsPopup']/div/div/div/div[1]/span[2]/img"))
  )

  # This waits up to 10 seconds before throwing a TimeoutException 
  # unless it finds the element to return within 10 seconds.

  if (DUP_popup):
    print ("Duplicate tkts popup is displayed - Fail")

except TimeoutException:
  print ("Duplicate popup not displayed - PASS")

有关显式等待和隐式等待的更多详细信息,请参见here

答案 1 :(得分:0)

不清楚为什么需要60秒才能提升 NoSuchElementException 并打印传递条件,但您可以通过服务员诱导来配置等待时间 WebDriverWait 如下:

driver.find_element_by_xpath(".//*[@id='assetIdDIV']/div/myaots-input/div/div/div[1]/span/i[2]").click()
if(len(WebDriverWait(driver, 20).until(EC.presence_of_all_elements_located((By.XPATH, ".//*[@id='DuplicateTicketsPopup']/div/div/div/div[1]/span[2]/img"))))!= 0):
    print ("Duplicate tkts popup is displayed - Fail")
else:
    print ("Duplicate popup not displayed - PASS")

注意:如果您的程序包含_implicitly_wait()_,则需要删除_implicitly_wait()_的实例,因为文档明确提到Do not mix implicit and explicit waits. Doing so can cause unpredictable wait times.

答案 2 :(得分:0)

检查您的驱动程序实例的隐式等待值。如果隐式值设置为60secs,那么它会等到60secs抛出任何与selenium相关的异常。