requests 库的另类用法(stream)

24 篇文章 0 订阅

重要
我的博客从今天起开始陆续迁移到
http://vearne.cc
敬请关注
本文链接
http://vearne.cc/archives/120

起因: 同事让我帮他抓取一批URL,并获取对应URL的标签中的文字,忽略对应URL网站的封禁问题,这个任务并不是一个特别麻烦的事情。然后实际跑起来,却发现流量打的很高,超过10Mb/s。

经过排查发现,是因为很多URL,实际是下载链接,会触发文件下载,这些URL对应的html中根本不会包含标签,那么处理逻辑就很清晰了,先拿到headers,取出Content-Type,判断是否是
text/html,如果不是,则该Response的body体,就没有必要读取了。

查找requests的相应资料

By default, when you make a request, the body of the response is
downloaded immediately. You can override this behaviour and defer
downloading the response body until you access the Response.content
attribute with the stream parameter:

tarball_url = 'https://github.com/kennethreitz/requests/tarball/master'
r = requests.get(tarball_url, stream=True)

At this point only the response headers have been downloaded and the
connection remains open, hence allowing us to make content retrieval
conditional:

if int(r.headers['content-length']) < TOO_LONG:
  content = r.content
  ...

只有headers头被下载了,body中的数据还没有被下载,这样就能避免不必要的流量开销,只有当你使用r.content 的时候,所有body内容才会被下载

You can further control the workflow by use of the
Response.iter_content() and Response.iter_lines() methods.
Alternatively, you can read the undecoded body from the underlying
urllib3 urllib3.HTTPResponse at Response.raw.

实时上还可以使用Response.iter_content() Response.iter_lines()
Response.raw()来自己决定要读取多少数据

重要
我的博客从今天起开始陆续迁移到
http://vearne.cc
敬请关注
本文链接
http://vearne.cc/archives/120

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值