Python3.5+requests 爬取网站遇到中文乱码怎么办?ä½œè€…ï¼šå¾®è½¯äºšæ´²ç ”ç©¶é™¢ 您所在的位置:网站首页 落日灯百度百科 Python3.5+requests 爬取网站遇到中文乱码怎么办?ä½œè€…ï¼šå¾®è½¯äºšæ´²ç ”ç©¶é™¢

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

2023-07-03 14:29| 来源: 网络整理| 查看: 265

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)

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

¿Æ˳¹É·Ý(300737) °Â·ÉÊý¾Ý(300738) Ã÷Ñôµç·(300739) Óù¼Ò»ã(300740) »ª±¦¹É·Ý(300741)

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



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有