python3的UnicodeDecodeError解決方法
更新時(shí)間:2019年12月20日 10:22:00 作者:__rookie
這篇文章主要介紹了python3的UnicodeDecodeError解決方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
爬蟲部分解碼異常
response.content.decode() # 默認(rèn)使用 utf-8 出現(xiàn)解碼異常

以下是設(shè)計(jì)的通用解碼
通過 text 獲取編碼
# 通過 text 獲取編碼
import requests
from lxml import etree
def public_decode():
headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36'
}
response = requests.get('https://blog.csdn.net/a13951206104', headers=headers)
html = etree.HTML(response.text) # response.text 能自動(dòng)獲取編碼, 大多亂碼
_charset = html.xpath('//@charset') or []
if _charset:
encode_content = response.content.decode(_charset[0].strip().lower(),
errors='replace') # 如果設(shè)置為replace,則會(huì)用?取代非法字符;
return {'response_text': encode_content, "response_obj": response}
for _charset_ in ['utf-8', 'gbk', 'gb2312'] # 國內(nèi)主要這3種:
if '�' not in response.content.decode(_charset_, errors='replace'):
return {'response_text': response.content.decode(_charset_, errors='replace'),
"response_obj": response}
else:
# 默認(rèn)還得是 utf-8
return {'response_text': response.content.decode('utf-8', errors='replace'),
"response_obj": response}
通過數(shù)據(jù) 來解編碼(推薦)
def public_decode(response):
headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36'
}
response = requests.get('https://blog.csdn.net/a13951206104', headers=headers)
html = etree.HTML(response.text)
# 不希望抓下來的數(shù)據(jù)中有非法字符
item = dict()
result = None
for _charset_ in ['utf-8', 'gbk', 'gb2312']:
if response:
result = response.content.decode(_charset_, errors='replace')
item['content'] = html.xpath('//*[@id="content"]')
if '�' not in result['content'].strip():
result =response.content.decode(_charset_, errors='replace')
break
if not result:
# 默認(rèn) utf-8
result = response.content.decode(_charset_, errors='replace')
errors=‘replace' 使解碼不報(bào)異常, 然后把幾個(gè)常用的編碼一個(gè)個(gè)試下, 最后要看落下來的數(shù)據(jù), 所以最好拿數(shù)據(jù) 去獲取合適的編碼
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
python中創(chuàng)建一個(gè)包并引用使用的操作方法
python包在開發(fā)中十分常見,一般通過導(dǎo)入包含特定功能的python模塊包進(jìn)行使用。當(dāng)然,也可以自己創(chuàng)建打包模塊,然后發(fā)布,安裝使用,這篇文章主要介紹了python中如何創(chuàng)建一個(gè)包并引用使用,需要的朋友可以參考下2022-08-08
Python繪圖之實(shí)現(xiàn)繪制極坐標(biāo)圖像
這篇文章主要介紹了如何利用python繪制極坐標(biāo)圖像,文中的示例代碼講解詳細(xì),具有一定的的參考價(jià)值,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下
2023-08-08
Python numpy多維數(shù)組實(shí)現(xiàn)原理詳解
這篇文章主要介紹了python numpy多維數(shù)組實(shí)現(xiàn)原理詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
2020-03-03 
