问题描述
我的程序在项目之间进行迭代,它单击该项目,然后再次单击并移至下一个项目。 如果出现错误,我正在尝试使程序通过某个项目。
例外位于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
因此,该代码的作用是,当发生任何错误时,无论是继续执行还是写入通过操作,循环都会从头开始重新开始。我只希望它跳过该项目。我想念吗?
解决方法
对于任何有相同问题的人,问题就是我在最后处理了异常。每个块都需要有自己的异常。代码应该是这样的:
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