Python3.5+requests 爬取网站遇到中文乱码怎么办?ä½œè€…ï¼šå¾®è½¯äºšæ´²ç ”ç©¶é™¢

import requests
from bs4 import BeautifulSoup

url = 'http://quote.eastmoney.com/stocklist.html'
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
headers = {'User-Agent': user_agent}
req = requests.get(url, headers=headers)
req.encoding = 'utf-8'
bs = BeautifulSoup(req.content, 'html.parser')  # type: BeautifulSoup
quotesearch = bs.find('div', attrs={'id': 'quotesearch'})
print(quotesearch)

运行以上代码,显示结果如下:

<li><a href="http://quote.eastmoney.com/sz300737.html" target="_blank">¿Æ˳¹É·Ý(300737)</a></li>
<li><a href="http://quote.eastmoney.com/sz300738.html" target="_blank">°Â·ÉÊý¾Ý(300738)</a></li>
<li><a href="http://quote.eastmoney.com/sz300739.html" target="_blank">Ã÷Ñôµç·(300739)</a></li>
<li><a href="http://quote.eastmoney.com/sz300740.html" target="_blank">Óù¼Ò»ã(300740)</a></li>
<li><a href="http://quote.eastmoney.com/sz300741.html" target="_blank">»ª±¦¹É·Ý(300741)</a></li>

1.解决思路一:查看网页的编码方式

F12打开网站地址,查看最上方head,发现编码方式为‘gb2312’(charset=gb2312),修改代码第八行req.encoding = 'gb2312',重新运行代码。运行结果未改变,仍有乱码。

2.解决思路二:修改代码第九行bs = BeautifulSoup(req.text, 'html.parser'),将req.content改为req.text,运行代码,结果正常,无乱码。

原理:

resp.text返回的是Unicode型的数据。
resp.content返回的是bytes型也就是二进制的数据

因此如果我们想读取解析文本数据时,使用的是response.text。而想读取解析图片文件,往往使用的就是response.content

转载自:https://blog.csdn.net/weixin_41931602/article/details/81181946

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值