python - 如果需要太长时间,则在 for 循环中跳过 selenium Webdriver.get() 调用
问题描述
嘿伙计们,我无法理解如何将异常添加到 for in range 循环中。现在,我正在从 Excel 工作表中提取 URL 并在整个页面中移动时抓取信息,直到到达第 200 页。问题是并非所有 URL 的页面都达到 200,因此循环结束需要很长时间,并且程序可以继续使用另一个 URL。有没有办法在这里的代码中实现异常?
from selenium import webdriver
import pandas as pd
import time
driver = webdriver.Chrome("C:/Users/Acer/Desktop/chromedriver.exe")
companies = []
df = pd.read_excel('C:/Users/Acer/Desktop/urls.xlsx')
for index, row in df.iterrows():
base_url = (row['urls'])
for i in range(1,201,1):
url = "{base_url}?curpage={i}".format(base_url=base_url, i=i)
driver.get(url)
time.sleep(2)
name = driver.find_elements_by_xpath('//a/div/div/p')
for names in name:
print(names.text, url)
companies.append([names.text, url])
解决方案
您可以在 Webdriver 上设置最大超时,然后Timeout
在循环中观察异常:
from selenium.common.exceptions import TimeoutException
MAX_TIMEOUT_SECONDS = 5
driver = webdriver.Chrome("C:/Users/Acer/Desktop/chromedriver.exe")
driver.set_page_load_timeout(MAX_TIMEOUT_SECONDS)
for i in range(1, 201):
try:
url = "{base_url}?curpage={i}".format(base_url=base_url, i=i)
driver.get(url)
except TimeoutException:
# skip this if it takes more than 5 seconds
continue
... # process the scraped URL as usual
如果发生超时,则通过 跳过当前迭代continue
。
推荐阅读
- continuous-integration - 如何打印/调试 GitLab CI 中包含的所有作业?
- python - 您如何查看内置变量以检查您的答案是否正确?Python
- html - 谷歌脚本没有检索 HTML textarea 提示的值
- chart.js - 如何在 Chart.js 轴标题中设置下标文本
- linux - Bash脚本按类型复制文件
- javascript - 为什么我不能在其中输入文字带有javascript代码的字段?文字闪回原值
- javascript - 在上传之前如何知道音频/视频的持续时间?
- laravel - 如何使用紧凑信息刷新 yajra 数据表?
- regex - 在 splunk 中打印 json 有效负载的字符串数组
- routes - 避免使用 MULTIPLE bbox 的区域 - Routing V8 REST API