前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python使用requests库做爬虫时,乱码问题解决方案

Python使用requests库做爬虫时,乱码问题解决方案

作者头像
IT工作者
发布2021-12-20 18:07:02
1.1K0
发布2021-12-20 18:07:02
举报
文章被收录于专栏:程序技术知识程序技术知识

一、获取网页内容

分析: res = requests.get(“http://www.baidu.com“) res.text返回的是Unicode型的数据。 使用res.content返回的是bytes型的数据。 也就是说,如果你想取文本,可以通过res.text。 如果想取图片,文件,则可以通过res.content。 方法1:使用res.content,得到的是bytes型,再转为str url='http://news.baidu.com' res = requests.get(url) html=res.content html_doc=str(html,'utf-8') #html_doc=html.decode("utf-8","ignore") print(html_doc) 方法2:使用res.text url="http://news.baidu.com" res=requests.get(url) res.encoding='utf-8' print(res.text) 方法3:使用res.text+apparent_encoding url="http://news.baidu.com" res=requests.get(url) res.encoding=res.apparent_encoding print(res.text)

二、获取内容后存入本地

方法1:r.content为bytes型,则open时需要open(filename,”wb”) res=requests.get("music.baidu.com") html=res.content withopen('test.html','wb') as f: f.write(html) 方法2:r.content为bytes型,转为str后存储 res = requests.get("http://www.baidu.com") html=res.content html_doc=str(html,'utf-8') #html_doc=html.decode("utf-8","ignore") withopen('test5.html','w',encoding="utf-8") as f: f.write(html_doc) 方法3:r.text为str,可以直接存储 res=requests.get("http://www.baidu.com") res.encoding='utf-8' html=res.text withopen('test.html','w',encoding="utf-8") as f: f.write(html)

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019-04-18 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档