我正在運(yùn)行一個(gè) Python 腳本,它使用值列表作為 API 端點(diǎn)上的 HTTP 請(qǐng)求的查詢參數(shù)。這里有一個(gè)快照:df = pd.read_excel('grp.xlsx', sheet_name='Sheet1', usecols="A")for item in df.PLACE: df.PLACE.head() #1st level request def wbsearchentities_q(**kwargs): params = { 'action': 'wbsearchentities', 'format': 'json', 'language': 'en', 'search': item } params.update(kwargs) response = requests.get(API_ENDPOINT, params=params) return response r = wbsearchentities_q(ids=item) item_id = (r.json()['search'][0]['id']) item_label = (r.json()['search'][0]['label']) 我遇到了這個(gè)錯(cuò)誤:IndexError: list index out of range這意味著 API 端點(diǎn)無(wú)法識(shí)別我列表中的某些項(xiàng)目。我會(huì)跳過(guò)并繼續(xù)循環(huán)。我試圖修復(fù)使用它沒(méi)有結(jié)果。提前致謝。
2 回答
BIG陽(yáng)
TA貢獻(xiàn)1859條經(jīng)驗(yàn) 獲得超6個(gè)贊
你可以試試:
for item in df.PLACE:
try:
... your code ...
except:
pass
慕容3067478
TA貢獻(xiàn)1773條經(jīng)驗(yàn) 獲得超3個(gè)贊
為了只針對(duì)那個(gè)錯(cuò)誤(推薦以避免不處理其他錯(cuò)誤),并繼續(xù)到下item一個(gè)df:
try:
item_id = (r.json()['search'][0]['id'])
item_label = (r.json()['search'][0]['label'])
except IndexError:
continue
添加回答
舉報(bào)
0/150
提交
取消
