gpt4 book ai didi

python - 使用 Python 请求的异步请求

转载 作者:行者123 更新时间:2023-12-01 19:52:45 28 4
gpt4 key购买 nike

我尝试了 requests library 文档中提供的示例对于Python。

使用async.map(rs),我得到了响应代码,但我想获取所请求的每个页面的内容。例如,这不起作用:

out = async.map(rs)
print out[0].content

最佳答案

注意

以下答案不适适用于 v0.13.0+ 的请求。异步功能已移至 grequests这个问题写完之后。但是,您只需将下面的 requests 替换为 grequests 就可以了。

我按原样保留了这个答案,以反射(reflect)有关使用请求< v0.13.0 的原始问题。

<小时/>

要使用 async.map 异步执行多个任务,您必须:

  1. 为您想要对每个对象执行的操作(您的任务)定义一个函数
  2. 将该函数作为事件 Hook 添加到您的请求中
  3. 在所有请求/操作的列表上调用 async.map

示例:

from requests import async
# If using requests > v0.13.0, use
# from grequests import async

urls = [
'http://python-requests.org',
'http://httpbin.org',
'http://python-guide.org',
'http://kennethreitz.com'
]

# A simple task to do to each response object
def do_something(response):
print response.url

# A list to hold our things to do via async
async_list = []

for u in urls:
# The "hooks = {..." part is where you define what you want to do
#
# Note the lack of parentheses following do_something, this is
# because the response will be used as the first argument automatically
action_item = async.get(u, hooks = {'response' : do_something})

# Add the task to our list of things to do via async
async_list.append(action_item)

# Do our list of things to do via async
async.map(async_list)

关于python - 使用 Python 请求的异步请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9110593/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com