错误时停止

时间:2015-09-15 02:09:52

标签: python selenium-webdriver web-scraping

在python中,我使用selenium来抓取网页。我需要重复点击一个按钮,直到没有按钮为止。到目前为止,我的代码如下:

count = 20

while count:
    driver.find_elements_by_class_name('buttontext')[0].click()
    count-=1

问题在于我实际上并不知道我需要执行多少次 - count = 20不正确。我真正需要的是它继续运行,直到命令遇到错误(IndexError: list index out of range),然后停止。我怎样才能做到这一点?

4 个答案:

答案 0 :(得分:1)

按照 EAFP approach - 进行无限循环,并在找不到元素后将其中断:

from selenium.common.exceptions import NoSuchElementException

while True:
    try:
        button = driver.find_element_by_class_name("buttontext")
        button.click()
    except NoSuchElementException:
        break

答案 1 :(得分:0)

你需要这个吗?

while True:
   try:
       driver.find_elements_by_class_name('buttontext')[0].click()

   except IndexError:
       break
  

try会尝试运行一些代码,except可以捕获您选择的错误。

     

如果您没有选择错误,except将捕获所有错误。 For more info

答案 2 :(得分:0)

您应该使用try statement来处理异常。它将运行您的代码,直到找到异常。您的代码看起来应该是这样的:

try:
    while True:
        click_function() 
except Exception: #as Exception being your error 
    got_an_error()  #or just a pass

答案 3 :(得分:0)

我会关注Selenium docs' recommendation并使用.findElements()

  

findElement不应该用于查找不存在的元素,请使用   findElements(By)并断言零长度响应。

buttons = driver.find_elements_by_class_name("buttontext")
while buttons:
    buttons[0].click()
    // might need a slight pause here depending on what your click triggers
    buttons = driver.find_elements_by_class_name("buttontext")