在进行批量查询时,如果不允许从特定的请求中获取数据,可以使用以下代码示例中的方法进行解决:
import requests
def make_batch_request(urls):
responses = []
for url in urls:
try:
response = requests.get(url)
if response.status_code == 200:
responses.append(response.json())
else:
print(f"Error: {response.status_code} - {response.content}")
except requests.exceptions.RequestException as e:
print(f"Error: {e}")
return responses
# 调用示例
urls = [
"https://api.example.com/data1",
"https://api.example.com/data2",
"https://api.example.com/data3",
"https://api.example.com/data4",
"https://api.example.com/data5"
]
responses = make_batch_request(urls)
print(responses)
在上述示例中,我们定义了一个make_batch_request
函数,该函数接受一个URL列表作为参数,并使用requests
库发送GET请求获取每个URL的响应数据。
在循环中,我们使用try-except
块来捕获任何可能的异常情况,如网络连接问题或无效的URL。如果请求成功,我们将响应数据以JSON格式添加到responses
列表中。
最后,我们打印出所有的响应数据。
请注意,上述代码仅为示例,您需要根据实际情况进行适当的修改和错误处理。