【发布时间】:2018-01-10 01:21:28
【问题描述】:
我正在尝试在 python 中使用 selenium 捕获一些网站元素,并且我正在使用 try/except 以防在该特定页面中找不到特定元素。这一切都很好,但是脚本仍然会抛出 NoSuchElementException,即使我期待它并且已经告诉脚本以某种方式处理它或通过它。
我认为唯一可能是一个问题是这个 try/except 嵌套在另一个 try/except 中,所以我是这样的
for month in (month_start, month_end):
for date in (date_start, date_end):
try: #this is just a general try in case there is a breakdown in finding one of the elements
driver.get(url)
results = driver.find_elements_by_xpath("""//*[@class="results"]/div""")
for result in results:
sample_element = result.find_element_by_xpath("blah").text
#seems to be where the problem starts
specific_element = ""
try:
#this is a specific element that I know may not exist
specific_element = result.find_element_by_xpath(""".//*[@class="specific"]/div""").text
except NoSuchElementException:
specific_element = ""
#I have tried pass instead as well with no luck
#throws an error here and won't continue if the specific element is not found
except:
#pretty much a copy of the above try with some changes
所以我通常认为我对 python 中的 try/except 函数有一个不错的理解,但这让我很头疼。“result in results”循环将愉快地继续,直到它找不到 specific_element 并抛出一个“selenium.common.exceptions.NoSuchElementException:消息:没有这样的元素:无法找到元素:”
如果嵌套在 try/except 中是整个问题的原因,您能否解释一下为什么会这样,并推荐一个我可以研究或实施的可能解决方案?或者也许我错过了一些基本的东西。
【问题讨论】:
-
你导入 NoSuchElementException 吗?
-
可能你使用了错误的
NoSuchElementException。也许还有另一个NoSuchElementException与您得到的名称相同。你能尝试显式导入from selenium.common.exceptions import NoSuchElementException吗? -
@NiyamatUllah 是的,我有。它甚至似乎无法识别 try/except,并且在尝试失败后不会继续到 except。我也试过“除了:”,但仍然抛出同样的错误。
-
你知道三重双引号的作用是什么吗?
-
@Rescis 据我了解,三重双引号与单双引号相同,但它可以包含换行符。对我个人而言,这只是在长行中突出显示字符串的一种简单方法。