python - 我无法捕获所有请求错误/异常。某些原因导致未知错误

标签 python python-requests

我使用 Requests 模块多次 ping 网页。

一开始工作正常,但其中大约 100 个调用停止工作,此后对网站的每个调用都失败。我想不通。

我以为我将其设置为使用 except requests.exceptions.RequestException 捕获所有可能的错误,但发生了其他无法由此捕获的错误。

我不确定您是否需要查看 header ,但它们是:(没有 cookie 或数据。数据插入到 url 字符串中)

headers = {}
headers['Host'] = 'www.wensite.ie'
headers['Connection'] = 'keep-alive'
headers['Accept'] = 'application/json, text/plain, */*'
headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36 OPR/63.0.3368.71'
headers['Sec-Fetch-Mode'] = 'cors'
headers['Sec-Fetch-Site'] = 'same-origin'
headers['Accept-Encoding'] = 'gzip, deflate, br'
headers['Accept-Language'] = 'en-US,en;q=0.9'
cookies = {}
data = {}

还有请求。我的 except 设置为捕获所有错误(我想?)

try:

    data = requests.get(f'https://www.website.com/api/search/name/{firstname}/surname/{surname}/eircode/{zipcode}/lang/en',headers = headers,cookies = cookies,data=data,timeout=5)

    data = data.json()

    if data['results']:
        print('**Record Found**\n\n------------------')
        return 'record found'
    else:
        print('record not found\n\n------------------')
        return 'record not found'

except requests.exceptions.RequestException as e:
    print('Exception Ecountered....\n')
    print(str(e))
    print('\n------------------')
    return str(e)

except:

    print('Unknown Error Encountered\n------------------')
    return 'Unknown Error'

最后一个 except 是我获取错误消息的地方。在大约 100 次调用中,每次尝试都会导致此错误。感觉这个网站屏蔽了我。但我不应该收到 HTTP 403 错误 或类似的东西吗?

如何诊断此问题以捕获每一个可能的错误?

顺便说一句,这不是官方 api,我正在“抓取”网站,每次调用之间会暂停 2 秒。

最佳答案

您应该不使用异常处理程序来处理请求的错误,而是通过检查状态代码来处理。如果响应内容不是正确的 JSON 对象,您还可以 try catch JSON 解码器错误(首先导入 json):

response = requests.get(f'https://www.website.com/api/search/name/{firstname}/surname/{surname}/eircode/{zipcode}/lang/en', headers=headers, cookies=cookies, data=data, timeout=5)
if response.status_code >= 400:
    message = 'Error from server: {} {}'.format(response.status_code, response.reason)
    print(message)
    return message
try:
    data = response.json()
except json.decoder.JSONDecodeError as e:
    message = 'Error decoding response content as JSON: {}'.format(e)
    print(message)
    return message

关于python - 我无法捕获所有请求错误/异常。某些原因导致未知错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57923901/

相关文章:

用于使用请求模块登录网站的 Python 3 脚本

使用 python 读取 jpg 时出现 Azure blob UnicodeDecodeError

python - 是否可以使用 PYQT5 中的元素创建一个类

Python 3.6 类型检查 : numpy arrays and use defined classes

python - 匹配数据存储查询中的所有记录

python - 通过 Python 的单个连接进行多个请求

python - 使用 requests-mock 捕获 URL 参数

python - 是否可以直接将对象字段初始化为 __init__ 关键字参数?

python - 如何提高数百个文件中数千行的解析效率

Python Mechanize 连接失败问题