python - 一般显式等待 - selenium python

标签 python selenium explicit

我希望这个问题是独一无二的,并且对其他测试人员也有帮助。
我需要 python selenium 的解决方案。
我需要通过时间显式等待替换几行 time.sleep() 代码。 当 Chrome 在每个预期被点击的元素之前休眠几秒钟时,测试将成功运行,否则,它会失败。

所以它是这样的:

driver.find_element_by_xpath("x").click()  
time.sleep(5)
driver.find_element_by_xpath("y").click()  
time.sleep(5)
driver.find_element_by_xpath("z").click()  
time.sleep(5)

...

当然,隐性等待是不够的。

推荐代码如下:

from selenium.webdriver.support import expected_conditions as EC

wait = WebDriverWait(driver, 10)
element = wait.until(EC.element_to_be_clickable((By.ID, 'someid')))

我查看了这个示例代码,但似乎我必须多次引用每个 ID,在我的例子中。

所以问题是:
是否有任何全局解决方案可以在不增加代码行的情况下对脚本中的每个元素使用显式等待?

最佳答案

不知道是不是你需要的。但是如果你愿意,你可以使用一个函数来尝试点击直到它成功或达到超时。这样,您只需调用它并等待即可。

import timeit
from selenium import webdriver

def safe_click(wd_elem, max_time=10):
    """
    wd_elem should be a WebElement object, so it has the .click() method
    max_time defaults to 10 [seconds], and it's how long will the script try to click before it stops
    """

    start = timeit.default_timer()
    while timeit.default_timer() - start <= max_time:
        try:
            wd_elem.click()
            return
        except:
            pass
    print 'Max time reached; stopped trying'

wd = webdriver.Chrome()
wd.get('https://stackoverflow.com/questions/48624119/general-explicit-wait-selenium-python')
elem_to_click = wd.find_element_by_xpath('//*[@id="question-header"]/h1/a')
safe_click(elem_to_click)  # Clicks it
safe_click(None)  # After 10 seconds, it gives up

如果你应用它,你的代码将是:

safe_click(driver.find_element_by_xpath("x")  # Leaving max_time equal to 10 seconds
safe_click(driver.find_element_by_xpath("y", max_time=5)  # Explicitly setting max_time to 5 seconds
safe_click(driver.find_element_by_xpath("z", max_time=9999)  # Explicitly setting max_time to 9999 seconds

关于python - 一般显式等待 - selenium python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48624119/

相关文章:

python - 与 AWS Lambda 重试失败函数相关的成本?

python - PyGObject 模板子项未定义

python - 通过 Selenium 和 Webdriver 循环遍历 find_element_by_xpath() 的元素列表

java - 检查 url 当前是否位于正确的位置以及格式正确的 id

Perl:全局符号需要显式包名称

c++ - 错误 : no matching function for call to . .. 在返回语句

python - Django/ Bootstrap 4 : How to align elements inside of multiple parent divs

python - 使用最新版本的 python 创建 virtualenv

python - 使用 Selenium Actionchains 时指定 Actions 之间的等待时间

c# - 为什么我不能使用带有显式运算符的接口(interface)?