[229]python3的requests类抓取中文页面出现乱码的解决办法
這種亂碼現象基本上都是編碼造成的,我們要轉到我們想要的編碼,先po一個知識點,嵩天老師在Python網絡爬蟲與信息提取說到過的:response.encoding是指從HTTP的header中猜測的響應內容編碼方式,如果header中不存在charset,則默認編碼為ISO-8859-1 ,這樣一來某些不規范的服務器返回就必然亂碼了;response.apparent_encoding是指從內容中分析出的響應內容編碼方式。requests內部的 utils 也提供了一個從返回 body 獲取頁面編碼的函數get_encodings_from_content,這樣如果服務器返回的頭不含 Charset,再通過 get_encodings_from_content 就可以知道頁面的正確編碼了。下面是調試的過程:
import requests from requests.exceptions import RequestExceptiondef get_one_page(url):try:response=requests.get(url)if response.status_code == 200:#print(response.text)print(response.encoding)print(response.apparent_encoding)r=response.textprint(requests.utils.get_encodings_from_content(r)[0])a=r.encode('ISO-8859-1').decode(requests.utils.get_encodings_from_content(r)[0])print(a)print('------------------------------------')b = r.encode('ISO-8859-1').decode(response.apparent_encoding)print(b)return Noneexcept RequestException:return Nonedef main():url = 'http://www.mh160.com/'get_one_page(url)if __name__=='__main__':main()看圖!看圖!看圖!
如果python抓取網頁后用decode解碼,報錯信息如下:
UnicodeDecodeError: ‘gb2312’ codec can’t decode byte 0xb0 in position 18020: illegal multibyte sequence
推測是網頁數據中有錯誤的字符無法解碼,decode有參數errors,設置一下就好啦~
html=etree.HTML(response.text.encode(response.encoding).decode(response.apparent_encoding,errors = 'ignore'))來源:https://www.jianshu.com/p/b535a9434120
總結
以上是生活随笔為你收集整理的[229]python3的requests类抓取中文页面出现乱码的解决办法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Pr安装完BCC插件后出现“找不到引入口
- 下一篇: websocket python爬虫_p