如何告訴我的程式跳過損壞/不存在的 URL 并繼續執行任務?每次我運行它時,它都會在遇到不存在的 URL 并給出錯誤時停止:index error: list index out of range。
范圍是介于 1 到 450 之間的 URL,但混合中的某些頁面已損壞(例如,URL 133 不存在)。
import requests
import pandas as pd
import json
from pandas.io.json import json_normalize
from bs4 import BeautifulSoup
df = pd.DataFrame()
for id in range (1, 450):
url = f"https://liiga.fi/api/v1/shotmap/2022/{id}"
res = requests.get(url)
soup = BeautifulSoup(res.content, "lxml")
s = soup.select('html')[0].text.strip('jQuery1720724027235122559_1542743885014(').strip(')')
s = s.replace('null','"placeholder"')
data = json.loads(s)
data = json_normalize(data)
matsit = pd.DataFrame(data)
df = pd.concat([df, matsit], axis=0)
df.to_csv("matsit.csv", index=False)
uj5u.com熱心網友回復:
我會假設您的索引錯誤來自帶有以下陳述句的代碼行:
s = soup.select('html')[0].text.strip('jQuery1720724027235122559_1542743885014(').strip(')')
你可以這樣解決它:
try:
s = soup.select('html')[0].text.strip('jQuery1720724027235122559_1542743885014(').strip(')')
except IndexError as IE:
print(f"Indexerror: {IE}")
continue
如果上面的行沒有發生錯誤,只需在發生索引錯誤的行上捕獲例外即可。或者,您也可以只捕獲所有例外
try:
code_where_exception_occurs
except Exception as e:
print(f"Exception: {e}")
continue
但我建議盡可能具體,以便您以適當的方式處理所有預期的錯誤。在上面的示例中,將 code_where_exception_occurs 替換為代碼。您也可以將 try/except 子句放在 for 回圈內的整個代碼塊周圍,但最好單獨捕獲所有例外。這也應該有效:
try:
url = f"https://liiga.fi/api/v1/shotmap/2022/{id}"
res = requests.get(url)
soup = BeautifulSoup(res.content, "lxml")
s = soup.select('html')[0].text.strip('jQuery1720724027235122559_1542743885014(').strip(')')
s = s.replace('null','"placeholder"')
data = json.loads(s)
data = json_normalize(data)
matsit = pd.DataFrame(data)
df = pd.concat([df, matsit], axis=0)
except Exception as e:
print(f"Exception: {e}")
continue
uj5u.com熱心網友回復:
主要問題是您獲得了一些網址204 error
(例如:https://liiga.fi/api/v1/shotmap/2022/405),因此只需使用它if-statement
來檢查和處理:
for i in range (400, 420):
url = f"https://liiga.fi/api/v1/shotmap/2022/{i}"
r=requests.get(url)
if r.status_code != 200:
print(f'Error occured: {r.status_code} on url: {url}')
#### log or do what ever you like to do in case of error
else:
data.append(pd.json_normalize(r.json()))
注意: 正如https://stackoverflow.com/a/73584487/14460824中已經提到的,不需要使用BeautifulSoup
,pandas
直接使用來保持代碼干凈
例子
import requests, time
import pandas as pd
data = []
for i in range (400, 420):
url = f"https://liiga.fi/api/v1/shotmap/2022/{i}"
r=requests.get(url)
if r.status_code != 200:
print(f'Error occured: {r.status_code} on url: {url}')
else:
data.append(pd.json_normalize(r.json()))
pd.concat(data, ignore_index=True)#.to_csv("matsit", index=False)
輸出
Error occured: 204 on url: https://liiga.fi/api/v1/shotmap/2022/405
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/507427.html
下一篇:超長鏈接的不同瀏覽器行為