【问题标题】:Iterating through reacquired list of elements遍历重新获取的元素列表
【发布时间】:2015-05-28 17:23:45
【问题描述】:

我有:两个未使用和已使用元素的列表。我必须从第一个到第二个传输确切的元素(可以通过双击或单击+按钮来传输元素,而不是从“未使用的元素”中消失并出现在“使用的元素”中)。发现每次传输元素时都会重新获取第一个列表。

for x in range(0, len(offers)):
    try:
        if "21796" in offers[x].get_attribute('text'):
            ActionChains(app.driver).double_click(offers[x]).perform()
            offers = app.driver.find_elements_by_css_selector('select[name="unused_offers[]"]>option')
    except IndexError:
        break

所以我在初始报价列表的长度范围内运行循环,有两个问题:

1) 如果我不重新获取“优惠”列表,我将获得StaleElementException

2) 如果这样做,我将超出初始报价列表范围,因为每次迭代的“报价”列表都会变短。

我决定通过 2) 方式,只处理 IndexError 异常。

问题:有没有更好的方法来遍历比迭代范围更短的列表?

我也试过了

ActionChains(app.driver).key_down(Keys.CONTROL, offers[x]).click(offers[x]).key_up(Keys.CONTROL, offers[x]).perform()

在重新获取转义列表的循环中,但出现了问题 - 循环只是一个一个地单击元素(看起来 CTRL 并没有真正保持。

【问题讨论】:

    标签: python list selenium selenium-webdriver


    【解决方案1】:

    我会创建一个“无限”循环,在每次迭代中找到一个报价,并在找不到报价时退出循环(引发NoSuchElementException 异常)。实施:

    from selenium.common.exceptions import NoSuchElementException
    
    while True:
        try:
            offer = app.driver.find_element_by_xpath('//select[@name="unused_offers[]"]/option[contains(@text, "21796")]')
        except NoSuchElementException:
            break
    
        ActionChains(app.driver).double_click(offer).perform()
    

    【讨论】:

      猜你喜欢
      • 2018-03-06
      • 2019-08-22
      • 1970-01-01
      • 2013-05-26
      • 1970-01-01
      • 2020-07-30
      • 2011-01-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多