如何从获取请求中获取响应状态码?

How to GET responde status code from get request?

您好,我是 python 编程的新手。在这里,我尝试编写一个 python 脚本,它将使用 GET 请求获取状态代码。我可以对单个 URL 执行此操作,但如何在单个脚本中对多个 URL 执行此操作。 这是我编写的基本代码,它将从 url.

获取响应代码
import requests
import json
import jsonpath

#API URL
url = "https://reqres.in/api/users?page=2"

#Send Get Request
response = requests.get(url)
if response:
    print('Response OK')
else:
    print('Response Failed')

# Display Response Content
print(response.content)
print(response.headers)

#Parse response to json format
json_response = json.loads(response.text)
print(json_response)

#Fetch value using Json Path
pages = jsonpath.jsonpath(json_response,'total_pages')
print(pages[0])

您可以通过response.status_code

访问状态码

您可以将代码放入这样的函数中

def treat_url(url):
    response = requests.get(url)
    if response:
        print('Response OK')
    else:
        print('Response Failed')

    # Display Response Content
    print(response.content)
    print(response.headers)

    #Parse response to json format
    json_response = json.loads(response.text)
    print(json_response)

    #Fetch value using Json Path
    pages = jsonpath.jsonpath(json_response,'total_pages')
    print(pages[0])

并有一个 url 列表并迭代抛出它:

url_list=["www.google.com","https://reqres.in/api/users?page=2"]
for url in url_list:
    treat_url(url)

试试这个代码。

import requests


with open("list_urls.txt") as f:
    for url in f:
           response = requests.get(url)
           print ("The url is ",url,"and status code is",response.status_code)

希望对您有所帮助。

几个建议,问题本身不是很清楚,所以一个好的表述对这里的所有贡献者都有用:) ...

现在说到我能够理解的内容,您可以做的修改很少:

response = requests.get(url) 你总是会得到一个响应对象,我想你可能想在这里检查状态代码,你可以通过 response.status_code 并根据你得到的,你说是否你是否得到了成功的回应。

关于循环,您可以检查响应 JSON 中的 last page 作为 response_json['last_page'] 和 运行 在 range(2, last_page + 1) 上的 for 循环并附加页面URI 中的数字以获取单个页面响应

您可以直接从响应对象 response.json() 中获取 JSON 请参考 requests 文档 here