使用 grequests 从异步请求中提取文本
Extracting Text From Asynchronus Request Using grequests
我正在尝试从我通过 grequest 库发出的请求中提取文本部分,但我不知道该怎么做。
如果我们使用 Requests Library 我会做
r = requests.get('www.google.com')
htmls.append(r.text)
现在,如果我使用 grequests,我只能得到一个响应代码列表,而不是文本。
rs = (grequests.get(u) for u in urls)
result = grequests.map(rs)
我试过的
result = grequests.map(rs.text)
我在使用上面的代码时遇到错误 AttributeError: 'generator' object has no attribute 'text'
我想要的输出是 html 文本的列表,其中响应代码是 200,否则值应该是 None。
我怎样才能做到这一点?
期望的输出:
response_code = [<Response [200]>,<Response [404]>,<Response [200]>]
htmls = ['html1', None, 'html2']
您可以使用类似下面的内容
rs = (grequests.get(u) for u in urls)
responses = grequests.map(rs)
text = list(map(lambda d : d.text if d else None, responses))
print(text)
调用地图后返回的是一个响应数组。然后您可以使用本机 map
函数
处理此数据
我正在尝试从我通过 grequest 库发出的请求中提取文本部分,但我不知道该怎么做。
如果我们使用 Requests Library 我会做
r = requests.get('www.google.com')
htmls.append(r.text)
现在,如果我使用 grequests,我只能得到一个响应代码列表,而不是文本。
rs = (grequests.get(u) for u in urls)
result = grequests.map(rs)
我试过的
result = grequests.map(rs.text)
我在使用上面的代码时遇到错误 AttributeError: 'generator' object has no attribute 'text'
我想要的输出是 html 文本的列表,其中响应代码是 200,否则值应该是 None。 我怎样才能做到这一点?
期望的输出:
response_code = [<Response [200]>,<Response [404]>,<Response [200]>]
htmls = ['html1', None, 'html2']
您可以使用类似下面的内容
rs = (grequests.get(u) for u in urls)
responses = grequests.map(rs)
text = list(map(lambda d : d.text if d else None, responses))
print(text)
调用地图后返回的是一个响应数组。然后您可以使用本机 map
函数