在一個 API 專案中作業,我試圖從 API 輸出(例如https://urlscan.io/api/v1/result/39a4fc22-39df-4fd5-ba13-21a91ca9a07d/)中獲取所有重定向網址
我試圖從中提取網址的示例:
"redirectResponse": {
"url": "https://www.coke.com/"
我目前有以下代碼:
import requests
import json
import time
#URL to be scanned
url = 'https://www.coke.com'
#URL Scan Headers
headers = {'API-Key':apikey,'Content-Type':'application/json'}
data = {"url":url, "visibility": "public"}
response = requests.post('https://urlscan.io/api/v1/scan/',headers=headers, data=json.dumps(data))
uuid = response.json()['uuid']
responseUrl = response.json()['api']
time.sleep(10)
req = requests.Session()
r = req.get(responseUrl).json()
r.keys()
for value in r['data']['requests']['redirectResponse']['url']:
print(f"{value}")
我收到以下錯誤:TypeError: list indices must be integers or slices, not str。不確定決議嵌套 json 以獲取所有重定向 url 的最佳方法是什么。
uj5u.com熱心網友回復:
AredirectResponse并不總是出現在 中requests,因此必須撰寫代碼來處理它并繼續運行。在 Python 中,通常用try/完成except:
for obj in r['data']['requests']:
try:
redirectResponse = obj['request']['redirectResponse']
except KeyError:
continue # Ignore and skip to next one.
url = redirectResponse['url']
print(f'{url=!r}')
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/314404.html
