1. 程式人生 > >Python3.5+requests 爬取網站遇到中文亂碼怎麼辦?ä½œè€…ï¼šå¾®è½¯äºšæ´²ç ”ç©¶é™¢

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