
使用 Python Requests 库处理异步请求
挑战:
虽然 Requests 库的文档提供了执行异步的示例请求,它缺乏检索页面内容的指导。以下代码无法访问内容:
1 2 | out = async.map(rs)
print out[0].content
|
登录后复制
解决方案:
要使用 async.map 执行多个异步任务,请按照以下步骤操作:
-
定义任务函数:创建一个函数来处理每个任务或响应对象。
-
添加事件挂钩:将此函数作为事件挂钩添加到请求中,以指定如何处理响应。
-
映射请求: 使用您希望执行的所有请求或操作的列表调用 async.map异步。
示例:
考虑 URL 列表和打印响应 URL 的简单任务:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | import async
urls = [
'http://python-requests.org' ,
'http://httpbin.org' ,
'http://python-guide.org' ,
'http://kennethreitz.com'
]
def do_something(response):
print (response.url)
async_list = []
for u in urls:
action_item = async.get(u, hooks={ 'response' : do_something})
async_list.append(action_item)
async.map(async_list)
|
登录后复制
以上是如何从Python请求库中的异步请求中检索页面内容?的详细内容。更多信息请关注PHP中文网其他相关文章!