如何解决使用grequests从异步请求中提取文本
我正在尝试从通过grequest库发出的请求中提取文本部分,但无法弄清楚该怎么做。
如果我们使用请求库,我会这么做
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']
解决方法
你可以使用类似下面的东西
<center> <img src="header.gif" alt="header"> </center>
<br> <img src="one.gif" alt="one" class="one-image">
<form action="https://www.freecatphotoapp.com/submit-cat-photo">
<div class="field">
<fieldset style="width: 300px; height: 180;">
<legend>Contact Details</legend>
<label for="fname">Name:</label> <br>
<input type="text" id="fname" name="fname"></br>
<label for="lname">Cell no.:</label> <br>
<input type="text" id="lname" name="lname"> </br>
<label for="email">Address:</label> <br>
<input type="email" id="email" name="email"><br>
</fieldset>
</div>
<br>
<br>
<input type="submit" value="Submit">
</form>
<br></br>
<img src="two.gif" alt="two">
<br></br>
<img src="three.gif" alt="three">
</div>
您返回的是调用地图后的响应数组。然后您可以使用本机 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)
函数
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。