Python Web 抓取一个元素 - 尝试直到成功,然后等待,然后重试

Python Web Scraping an element- try until it works, then wait, and try again

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

我可能会有一个带有 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

您可能需要这个 导入 :

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