深度阅读

How to retrieve the status code of an HTTP response in Python?

作者
作者
2023年08月22日
更新时间
9.81 分钟
阅读时间
0
阅读量

To retrieve the status code of an HTTP response in Python, you can use the status_code attribute of the response object returned by the requests library. Here’s an example:

import requests

response = requests.get('https://www.google.com')
status_code = response.status_code

if status_code == 200:
    print('The request was successful!')
else:
    print(f'The request failed with status code {status_code}')

In this example, we send a GET request to https://www.google.com and store the response object in the response variable. The status code of the response is then retrieved using the status_code attribute, and we use it to determine whether the request was successful or not.

The status_code attribute returns an integer representing the status code of the response, such as 200 for a successful request or 404 for a resource not found error. More information about the different status codes can be found in the HTTP/1.1 specification, RFC 7231.

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。