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