Python:如何发送多个HTTP请求并接收响应? [英] Python: How can i send multiple HTTP requests and receive the response?
本文介绍了Python:如何发送多个HTTP请求并接收响应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何以最快的方式发送1000个请求?
我知道您可以使用grequests
发送多个请求:
How can I send like 1000 requests the fastest way?
I know that you can send multiple request with grequests
:
urls = [
'sample.url/1',
'sample.url/2',
...
]
request = (grequests.get(u) for u in urls)
print grequests.map(request)
但是返回的不是内容. 我需要获取json数据,例如这样的东西:
But the return is not the content. What I need is to get the json data, so for example something like this:
request = (grequests.get(u) for u in urls)
content = grequests.json(request)
推荐答案
返回的项目不是内容,但确实包含内容.您可以像这样获取所有内容:
The items returned are not the content, but they do include the content. You can fetch all of the content like so:
result = grequests.map(request)
content = '\n'.join(r.content for r in result) # raw content
text = '\n'.join(r.text for r in result) # decoded content
您可以像这样解析json:
You can parse the json like this:
result = grequests.map(request)
json = [r.json() for r in result]
示例程序:
import grequests
import pprint
urls = [
'http://httpbin.org/user-agent',
'http://httpbin.org/headers',
'http://httpbin.org/ip',
]
requests = (grequests.get(u) for u in urls)
responses = grequests.map(requests)
json = [response.json() for response in responses]
pprint.pprint(json)
text = '\n'.join(response.text for response in responses)
print(text)
这篇关于Python:如何发送多个HTTP请求并接收响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文