Python Selenium Webdriver检查元素是否不存在需要时间

Python Selenium Webdriver检查元素是否不存在需要时间,python,selenium,selenium-webdriver,xpath,Python,Selenium,Selenium Webdriver,Xpath,尝试在几次GUI操作后验证某些按钮不存在(预计不存在)。我使用的是通过xpath()查找元素,但速度非常慢。任何超时解决方案?实际上,如果找不到指定的元素,WebDriver的find\u element方法将等待元素的隐式时间 WebDriver中没有像isElementPresent()这样的预定义方法可供检查。你应该为此写下自己的逻辑 逻辑 public boolean isElementPresent() { try { set_the_implicit time

尝试在几次GUI操作后验证某些按钮不存在(预计不存在)。我使用的是通过xpath()查找元素,但速度非常慢。任何超时解决方案?

实际上,如果找不到指定的元素,WebDriver的find\u element方法将等待元素的隐式时间

WebDriver中没有像isElementPresent()这样的预定义方法可供检查。你应该为此写下自己的逻辑

逻辑

public boolean isElementPresent()
{
   try
   {
      set_the_implicit time to zero
      find_element_by_xpath()
      set_the_implicit time to your default time (say 30 sec)
      return true;
   }
   catch(Exception e)
   {
       return false;
   }
}

请参阅:

如果要检查元素是否不存在,最简单的方法是使用
with
语句

from selenium.common.exceptions import NoSuchElementException

def test_element_does_not_exist(self):
    with self.assertRaises(NoSuchElementException):
        browser.find_element_by_xpath()
至于超时时间,我喜欢来自的那个


向我们展示代码,你是如何做到的?是的,这里精确的xpath表达式很重要,在python中如何做到这一点<代码>驱动程序。隐式等待(0)不做任何更改。似乎它保留了第一次调用中给定的值。
# Set to however long you want to wait.
MAX_WAIT = 5

def wait(fn):  
    def modified_fn(*args, **kwargs):  
        start_time = time.time()
        while True:  
            try:
                return fn(*args, **kwargs)  
            except (AssertionError, WebDriverException) as e:  
                if time.time() - start_time > MAX_WAIT:
                    raise e
            time.sleep(0.5)
    return modified_fn


@wait
def wait_for(self, fn):
    return fn()

# Usage - Times out if element is not found after MAX_WAIT.
self.wait_for(lambda: browser.find_element_by_id())