【问题标题】:How to GET responde status code from get request?如何从获取请求中获取响应状态码?
【发布时间】:2020-03-08 08:13:53
【问题描述】:

您好,我对 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])

【问题讨论】:

    标签: python url get endpoint


    【解决方案1】:

    试试这个代码。

    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)
    

    我希望这会有所帮助。

    【讨论】:

    • 谢谢它的工作。假设一个案例。我将所有网址保存在一个文件中,例如:url.list,我想在 python 脚本中调用该文件(url.list)。是否可以?因为我有超过 100 个网址要检查。我知道如何在 shell 中做到这一点,但不是在 python 中,请帮助我
    • @SameerSheik 我已根据您的要求更改了代码。 list_urls.txt 文件代表 100 多个 urls 文件。现在你可以得到每个网址https status code
    【解决方案2】:

    您可以使用 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)
    

    【讨论】:

    • 感谢天使,它可以工作,但我的问题是如何一次遍历多个 url,假设 100 可能是
    【解决方案3】:

    一些建议,问题本身不是很清楚,所以在这里的所有贡献者都会有一个很好的表达方式:) ...

    现在说到我能理解的,你可以做一些修改:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-28
      • 2017-04-01
      • 1970-01-01
      • 2011-07-17
      • 2014-07-17
      • 1970-01-01
      • 2020-08-19
      • 2020-01-10
      相关资源
      最近更新 更多