嗨,我是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
import json
urls = ['https://reqres.in/api/users?page=1','https://reqres.in/api/users?page=2','https://reqres.in/api/users?page=3']
for url in urls:
response = requests.get(url)
print ("The url is ",url,"and status code is",response.status_code)
output:
The url is https://reqres.in/api/users?page=1 and status code is 200
The url is https://reqres.in/api/users?page=2 and status code is 200
The url is https://reqres.in/api/users?page=3 and status code is 200
我希望这会有所帮助。
一些建议,问题本身不是很清楚,因此,对于此处的所有贡献者来说,良好的表达方式将很有用:) ...
现在我能理解的是,您可以做一些修改:
response = requests.get(url)
您将始终获得一个响应对象,我想您可能想在此处检查状态代码,您可以通过response.status_code
来执行此操作,并根据获得的结果说出是否获得成功响应。
您可以直接从响应对象response.json()
中获取json请参考requests
doc here