Http Error 403: Forbidden with 异常处理

Http Error 403: Forbidden with exception handling

我试图从 github api 中删除数据 我有将近 1500 个这样的链接 Example link

我收到 HTTP 错误 403:禁止访问

任何人告诉我如何在 python 中使用异常处理来处理它?

这里是示例代码

for link in author_url:
        if link=="None found":
            continue
        link = Request(link,headers={'Accept': 'application/vnd.github.v3+json'}) 
        response = urlopen(link) 
        raw_json = response.read().decode("utf-8") 
        author_data = json.loads(raw_json)

如果不知道您为该 Request 对象和 openurl 方法使用了哪些包,则很难知道处理它的正确方法。我假设您使用的是 urllib.

我会在 urlopen(link) 周围放置一个 try/except 以捕获请求中发生的任何错误。

像这样的东西适用于 urllib:

for link in author_url:
        if link=="None found":
            continue
        link = Request(link,headers={'Accept': 'application/vnd.github.v3+json'})
    try:
        response = urlopen(link) 
    except HTTPError as e:
        if e.code == 403:
            # Handle error here
    raw_json = response.read().decode("utf-8") 
    author_data = json.loads(raw_json)