python - 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 部分,它就会卡在循环中。我们如何解决这个问题?
解决方案
我可能会有一个 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
推荐阅读
- android - 我想使用Android App从firebase中单独获取所有数据
- android - “android:windowLightStatusBar”不起作用
- vue.js - 在 Quasar/Vue 中触发/更新从子组件到父组件的数据更改,以防子组件具有项目列表
- java - 禁用 Spring Cloud 配置客户端
- javascript - 如何使用 Vue CLI 一次将多个 Vue.js 组件构建为原生 Web 组件?
- laravel - 关闭浏览器时,Laravel 登录过期
- git - 如何在 GitLab-runner 中使用 Git 命令?
- html - 如何在 Django 中实现特定于对象的模式?
- python - 当有其他参数时如何在Django中绑定表单
- php - Ionic Angular Query 字符串解析以登录