【问题标题】:Python Web Scraping an element- try until it works, then wait, and try againPython Web Scraping an element-尝试直到它工作,然后等待,然后再试一次
【发布时间】:2021-08-15 11:23:40
【问题描述】:

下面的代码运行完美,但 10 秒后我得到一个异常(表示找不到元素),那是因为元素正在刷新。刷新时间不到 1 秒。 所以我需要做的就是等待它刷新,然后继续。

items = driver.find_elements_by_class_name('box')

for item in items:
    while True:
        try:
            title = item.find_element_by_class_name('title').text
            break
        except:
            time.sleep(4)
            pass

我尝试用 try: except: 解决它,但是一旦它加入了 except 部分,它就会卡在循环中。我们如何解决这个问题?

【问题讨论】:

    标签: python selenium selenium-webdriver web-scraping try-except


    【解决方案1】:

    我可能会有一个find_elements 的 if 条件,如下所示:

    for item in items:
      while True:
        try:
          if len(driver.find_elements(By.CLASS_NAME, "title")) > 0:
            title = item.find_element_by_class_name('title').text
            break
          else:
            print("Elemennt could not be found")
        except NoSuchElementException as error:
          time.sleep(4)
          print("Something went wrong")
          pass
    

    你可能需要这个import

    from selenium.common.exceptions import TimeoutException, WebDriverException, NoSuchElementException
    

    【讨论】:

    • 它向我显示此错误 TabError: 在标题行的缩进中使用制表符和空格不一致 = item.find_element_by_class_name('title').text
    • @DisplayMoto :尝试上面的更新代码,应该可以帮助您解决问题。
    猜你喜欢
    • 1970-01-01
    • 2017-04-28
    • 2010-11-23
    • 2021-07-16
    • 1970-01-01
    • 1970-01-01
    • 2014-05-06
    • 2016-02-24
    • 1970-01-01
    相关资源
    最近更新 更多