嘿伙計們,我無法理解如何向 for in range 循環添加異?!,F在,我正在從 Excel 工作表中提取 URL,并在整個頁面中移動時抓取信息,直到到達第 200 頁。問題是,并非所有 URL 的頁面都達到 200,因此需要很長時間才能循環結束,并且程序可以使用另一個 URL 繼續。有沒有辦法在這里的代碼中實現異常?from selenium import webdriverimport pandas as pdimport timedriver = 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])
1 回答

紅糖糍粑
TA貢獻1815條經驗 獲得超6個贊
您可以在 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。
添加回答
舉報
0/150
提交
取消