代码之家  ›  专栏  ›  技术社区  ›  bill999

出错时停止

  •  0
  • bill999  · 技术社区  · 9 年前

    在python中,我使用硒来抓取网页。有一个按钮,我需要反复单击,直到不再有按钮。到目前为止,我的代码如下:

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

    问题是我不知道我需要做多少次- count = 20 不正确。我真正需要的是让它继续运行,直到命令遇到错误( IndexError: list index out of range ),然后停止。我该怎么做?

    4 回复  |  直到 9 年前
        1
  •  1
  •   alecxe    9 年前

    遵循 EAFP approach -创建一个无休止的循环,并在没有找到元素时将其断开:

    from selenium.common.exceptions import NoSuchElementException
    
    while True:
        try:
            button = driver.find_element_by_class_name("buttontext")
            button.click()
        except NoSuchElementException:
            break
    
        2
  •  0
  •   Lucas Menicucci    9 年前

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

    try:
        while True:
            click_function() 
    except Exception: #as Exception being your error 
        got_an_error()  #or just a pass
    
        3
  •  0
  •   JeffC    9 年前

    我会按照 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")
    
        4
  •  0
  •   Remi Guan cdlane    9 年前

    你需要这个吗?

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

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

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