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

一、获取网页内容

分析:
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)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值