python - 异常后在while循环中继续for循环?
问题描述
我正在尝试使用 Selenium 来抓取一堆网站,这些网站需要向下滚动并单击一个按钮。每个 url 具有相同的结构,但具有不同的点击次数。
我的代码:
for url in url_list:
while True:
wd.get(url)
last_height = wd.execute_script("return document.body.scrollHeight")
while True:
wd.execute_script("window.scrollTo(0, document.body.scrollHeight);")
#time.sleep = time for waiting
time.sleep(3)
new_height = wd.execute_script("return document.body.scrollHeight")
if new_height == last_height:
break
last_height = new_height
next_button = wd.find_element_by_link_text('next >>')
next_button.click()
但是,代码只完成了第一个 url 并返回错误:“NoSuchElementException”。它没有继续循环,有时如果我更改了 url 列表,它会在循环中间停止并出现错误:“ElementClickInterceptedException”
我的目标是继续并完成循环,并忽略错误。
如何改进代码?提前致谢
解决方案
WebDriverWait
归纳() 和() 并使用try..exceptelement_to_be_clickable
块如果找到元素然后单击 else 中断。
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
url_list = ['https://pantip.com/profile/2892172#topics','https://pantip.com/profile/5239396#topics','https://pantip.com/profile/349866#topics']
wd=driver=webdriver.Chrome()
for url in url_list:
print(url)
wd.get(url)
while True:
wd.execute_script("window.scrollTo(0, document.body.scrollHeight);")
try:
next_button=WebDriverWait(wd,10).until(EC.element_to_be_clickable((By.CSS_SELECTOR,'a.next.numbers')))
next_button.click()
except:
print("No more pages")
break
driver.quit()
推荐阅读
- ios - Braintree one time payment request taking too much time to load
- prometheus - Prometheus 黑盒导出器引用每个作业的几个模块
- bash - 如何使用 Bash 检查 UID 是否唯一?
- php - Laravel - 从控制器中的 API 获取返回的数据
- java - how, using retrofit2, confirm a GET request with a certificate (root -> ca -> my)
- powerbi - 在查询编辑器步骤之前应用过滤器
- google-bigquery - 如果键为空,则 BigQuery 嵌套表从嵌套表中删除
- jquery - 从 Select2 中获取选定的值
- javascript - 反应路由器 dom 库不适用于我的项目
- javascript - 在 Electron 应用程序中动态加载 JavaScript 代码/文件