我正在尝试处理来自http响应的异常。
问题与我的代码是我被迫使用和IF条件来捕获http错误代码
{ "_id" : ObjectId("576948b163a37b378dc21565"), "cuisine" : "Italian", "name" : "Vella", "restaurant_id" : "41704620", "grades" : [ { "grade" : "A", "score" : 11 }, { "grade" : "B", "score" : 17 } ], "address" : { "building" : "1480", "street" : "2 Avenue", "zipcode" : "10075", "coord" : [ -73.9557413, 40.7720266 ] }, "borough" : "Manhattan" }
我不相信这是正确的方法,我正在尝试以下
if page.status_code != requests.codes.ok:
page.raise_for_status()
这总是打印"什么都没发生",我如何能够捕获与GET URL相关的所有可能的异常?
答案 0 :(得分:1)
如果你想捕捉所有例外情况,你可以抓住RequestException:
import requests
try:
r = requests.get(........)
except requests.RequestException as e:
print(e.message)