浅析requests库响应对象的text和content属性
在做爬虫时请求网页的requests库是必不可少的,我们常常会用到 res = resquests.get(url) 方法,在获取网页的html代码时常常使用res的text属性: html = res.text,在下载图片或文件时常常使用res的content属性: with open(filename, fp.write(res.content)
下面我们来看看 'text' 和 'content' 的不同之处: 输出本博客的响应对象的 text url = <span style="color: #800000">'<span style="color: #800000">https://www.cnblogs.com/huwt/<span style="color: #800000">'<span style="color: #000000">
res = requests.get(url,timeout = 6<span style="color: #000000">) <span style="color: #0000ff">print(res.text) ?(只截取到 输出本博客的响应对象的 content url = <span style="color: #800000">'<span style="color: #800000">https://www.cnblogs.com/huwt/<span style="color: #800000">'<span style="color: #000000">
res = requests.get(url,timeout = 6<span style="color: #000000">) <span style="color: #0000ff">print(res.content) ?(只截取到 ? 通过 为了让进一步了解text 和 content 我们来看看它们的类型: url = <span style="color: #800000">'<span style="color: #800000">https://www.cnblogs.com/huwt/<span style="color: #800000">'<span style="color: #000000">
res = requests.get(url,timeout = 6<span style="color: #000000">) <span style="color: #0000ff">print<span style="color: #000000">(type(res.text)) <span style="color: #0000ff">print(type(res.content)) ? 我们可以看到res.text是字符串类型,而res.content是二进制类型 为了进一步验证我们使用bytes类型的decode()方法对content进行‘utf-8’编码再显示 <div class="cnblogs_code"> url = <span style="color: #800000">'<span style="color: #800000">https://www.cnblogs.com/huwt/<span style="color: #800000">'<span style="color: #000000"> 发现和res.text显示的内容完全一样 因此我们可以得出结论: resp.content返回的是bytes型也就是二进制的数据。、
获取文本一般使用res.text,获取图片或文件一般使用res.conten 再做几点补充: 在返回text时requests会基于 HTTP 头部对响应的编码作出有根据的推测,但不一定准确,有可能出现乱码,
而我们可以手动指定一种编码方式:res.encoding = <span style="color: #800000">'<span style="color: #800000">需要的编码方式<span style="color: #800000">'<span style="color: #000000">或让requests根据body进行猜测:res.encoding = res.apparent_encoding 参考学习: https://zhidao.baidu.com/question/941417472703558372.html https://www.cnblogs.com/loveyouyou616/p/8135678.html https://www.cnblogs.com/chownjy/p/6625299.html https://www.jianshu.com/p/0e0336b370f3 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |