Skip to main content
 首页 » 编程设计

python之一般显式等待之selenium python

2025年01月19日10lyhabc

我希望这个问题是独一无二的,并且对其他测试人员也有帮助。
我需要 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