如何在Python中生成异步HTTP GET请求并将响应对象传递给函数

2024-06-30 16:52:08 发布

您现在位置:Python中文网/ 问答频道 /正文

更新:Problem was incomplete documentation, event dispatcher passing kwargs to the hook function.

我有一个大约3万个网址的列表,我想检查各种字符串。我有一个使用Requests&;BeautifulSoup的脚本的工作版本,但它不使用线程或异步请求,因此速度非常慢。

最后,我想做的是缓存每个URL的html,这样我就可以运行多个检查,而不必向每个站点发出多余的HTTP请求。如果我有一个函数来存储html,那么异步发送HTTP GET请求然后传递响应对象的最佳方法是什么?

我一直在尝试使用grequest(as described here)和“hooks”参数,但是我得到了错误和documentation doesn't go very in-depth。所以我希望有经验的人能给我们一些启示。

下面是一个简单的例子,说明我要完成的任务:

import grequests

urls = ['http://www.google.com/finance','http://finance.yahoo.com/','http://www.bloomberg.com/']

def print_url(r):
    print r.url

def async(url_list):
    sites = []
    for u in url_list:
        rs = grequests.get(u, hooks=dict(response=print_url))
        sites.append(rs)
    return grequests.map(sites)

print async(urls)

它会产生以下类型错误:

TypeError: print_url() got an unexpected keyword argument 'verify'
<Greenlet at 0x32803d8L: <bound method AsyncRequest.send of <grequests.AsyncRequest object at 0x00000000028D2160>>
(stream=False)> failed with TypeError

不知道它为什么默认情况下发送“verify”作为关键字参数;如果有人有任何建议(使用grequests或其他方式),请共享:)

提前谢谢。


Tags: incomhttpurl参数htmldocumentationwww