Skip to main content
 首页 » 编程设计

python之Selenium/Python 做 n 次

2025年05月04日19lyhabc

我面临以下问题: 我需要一个在一个范围内随机生成 xpath 并单击它,然后检查一个元素是否存在,如果存在则使用另一个函数。否则返回并重试。

found = False 
        while not found: 
            rndm = random.choice(article_list) 
            random_link = driver.find_element_by_xpath("html/body/section/div[4]/div[1]/div/aside[%s]/a" % (rndm)) 
            random_link.click() 
            try: 
                driver.find_element_by_css_selector("element").is_displayed() 
                self.check() #function which check if the element is ok 
                found = True 
            except NoSuchElementException: 
                driver.back() 

它可以工作,但它使用了 while 循环。我需要限制它进行一定数量的尝试吗?任何建议如何去做?我试过:

for _ in itertools.repeat(None, N): 

但是当尝试 N 次后仍未找到某个元素时,测试不会落下并断言为 True。当它找到并通过 self.check 函数检查并且一切正常时,我收到 NoSuchElement 错误。

请您参考如下方法:

"I need to restrict it for a certain amount of tries?"

由于现有代码已经可以运行,您可以尝试添加新逻辑,同时尽量保持现有代码不变。除了检查 found 变量之外,一种可能的方法是使用计数器变量并检查计数器,如下所示:

found = False 
counter = 0 
max_tries = 10 
while not found and counter < max_tries: 
    counter += 1 
    ...... 
    try: 
        ...... 
        self.check() #function which check if the element is ok 
        found = True 
    except NoSuchElementException: 
        driver.back()