首页 > 解决方案 > Python Web Scraping an element - 尝试直到它工作,然后等待,然后再试一次

问题描述

下面的代码运行完美,但 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 部分,它就会卡在循环中。我们如何解决这个问题?

标签: pythonseleniumselenium-webdriverweb-scrapingtry-except

解决方案


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

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

您可能需要此导入

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

推荐阅读