【问题标题】:trying to use continue or pass inside while loop but it doesnt seem to do work selenium尝试使用 continue 或在 while 循环内部传递,但它似乎不起作用 selenium
【发布时间】:2020-12-18 03:20:24
【问题描述】:

我的程序在项目之间迭代,它单击项目,然后再次单击并移动到下一个项目。 如果出现错误,我正在尝试让程序传递一个项目。

例外都在一个while循环中,每个项目代码如下所示:

item_1 = driver.find_element_by_id('feed_item_0')
    item_1.location_once_scrolled_into_view
    if item_1.is_displayed():
        item_1.click()
    time.sleep(2)
    phone_reveal_1 = driver.find_element_by_id('phone_number_0')
    contact_seller_1 = driver.find_element_by_id('contact_seller_0')
    if phone_reveal_1.is_displayed():
        phone_reveal_1.click()
    elif contact_seller_1.is_displayed():
        contact_seller_1.click()

    elif not phone_reveal_1.is_displayed() or contact_seller_1.is_displayed():
        continue

最后我写了这个:

except selenium.common.exceptions.NoSuchElementException:
    continue
except selenium.common.exceptions.ElementClickInterceptedException:
    continue
except selenium.common.exceptions.StaleElementReferenceException:
    continue

所以代码的作用是当发生任何错误时,无论是否写入 continue 或 pass,循环都会从头开始重新开始。我只是希望它跳过项目什么。我失踪了吗?

【问题讨论】:

  • 可能是第二个if 可能是elif
  • 谢谢,它不会起作用,因为它是一个新的声明

标签: python selenium while-loop continue except


【解决方案1】:

对于任何有同样问题的人来说,问题是我最后处理了异常。每个块都需要有自己的异常。代码应该是这样的:

try:

    item_1 = driver.find_element_by_id('feed_item_0')
    item_1.location_once_scrolled_into_view
    if item_1.is_displayed():
        item_1.click()
    time.sleep(2)
    phone_reveal_1 = driver.find_element_by_id('phone_number_0')
    contact_seller_1 = driver.find_element_by_id('contact_seller_0')
    if phone_reveal_1.is_displayed():
        phone_reveal_1.click()
    elif contact_seller_1.is_displayed():
        contact_seller_1.click()
    phone_numbers_1 = driver.find_elements_by_id('phone_number_0')
    number_1 = [i.text for i in phone_numbers_1]

except NoSuchElementException:
    pass

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-28
    • 2016-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多