想请教一下python爬虫乱码的问题

qq_33783684 2017-12-01 01:24:23
请求https://www.zhihu.com/explore页面,但都是乱码
代码:
s = requests.session()
headers = {
'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
'Accept-Encoding': 'gzip, deflate, br',
'Accept-Language': 'zh-CN,zh;q=0.9',
'authorization': 'oauth c3cef7c66a1843f8b3a9e6a1e3160e20',
'Connection': 'keep-alive',
'Host': 'www.zhihu.com',
'Referer': 'https://zhuanlan.zhihu.com/p/30922625',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36'
}
s.headers = headers
res = s.get('https://www.zhihu.com/explore')
print(res.encoding)
print(res.text)

控制台都是乱码:

...全文
208 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
CaiNiaoWuZui 2017-12-01
  • 打赏
  • 举报
回复
如果不想去掉 'Accept-Encoding':'gzip, deflate, sdch, br', 那么由于数据采用了brotli压缩,那么需要导入模块brotli来解压 import brotli brotli.decompress(res.content).decode("utf-8") 即可
混沌鳄鱼 2017-12-01
  • 打赏
  • 举报
回复
主要是因为你的headers里设置了接受压缩,去了就可以了。 改成下面这样。

import requests
s = requests.session()
headers = {
        'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
        'authorization': 'oauth c3cef7c66a1843f8b3a9e6a1e3160e20',
        'Connection': 'keep-alive',
        'Host': 'www.zhihu.com',
        'Referer': 'https://zhuanlan.zhihu.com/p/30922625',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36'
}
s.headers = headers
res = s.get('https://www.zhihu.com/explore')
res.encoding = 'utf-8'
print(res.text)

qq_33783684 2017-12-01
  • 打赏
  • 举报
回复
引用 1 楼 xpresslink 的回复:
print(res.text.decode('utf-8'))
直接报错了 Traceback (most recent call last): File "F:/WorkSpace/Project/Python/PythonSpider/ZhiHuUserSpider/qwer.py", line 18, in <module> print(res.text.decode('utf-8')) AttributeError: 'str' object has no attribute 'decode'
混沌鳄鱼 2017-12-01
  • 打赏
  • 举报
回复
print(res.text.decode('utf-8'))

37,722

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧