UnicodeEncodeError: ‘gbk’ codec can’t encode character u’\u200e’ in position 43: illegal multib


【問題】

在執行代碼時,提示上述錯誤,源碼如下:

 1 # 下載小說...
 2 def download_stoy(crawl_list,header):
 3 
 4     # 創建文件流,將各個章節讀入內存
 5     with open('E:\盜墓test22.txt', 'w') as f:
 6         for each_url in crawl_list:
 7             # 有的時候訪問某個網頁會一直得不到響應,程序就會卡到那里,我讓他0.6秒后自動超時而拋出異常
 8             while True:
 9                 try:
10                     request = urllib.request.Request(url=each_url, headers=header)
11                     with urllib.request.urlopen(request, timeout=0.6) as response:
12                         html = response.read().decode('utf-8')
13                         break
14                 except:
15                     # 對於抓取到的異常,讓程序停止1.1秒,再循環重新訪問這個鏈接,訪問成功時退出循環
16                     time.sleep(1.1)
17 
18             # 匹配文章標題
19             title_req = re.compile(r'<h1>(.+?)</h1>')
20             # 匹配文章內容,內容中有換行,所以使flags=re.S  re.S表示跨行匹配
21             #content_req = re.compile(r'<div class ="content-body">(.+)</div>', re.S)
22             content_req = re.compile(r'<p>(.*?)</p>', re.S)
23             #"<div[^>]+>.+?<div>(.+?)</div></div>", re.I
24             #content_req = re.compile(r'<div[^>]+>.+?<div>(.+?)</div></div>', re.S)
25             # 獲取標題
26             title = title_req.findall(html)[0]
27             # 獲取內容
28             content_test = content_req.findall(html)
29             print('抓取章節>' + title)
30             f.write(title + '\n')
31             #print(content_test)
32             for each in content_test:
33                 # 篩除不需要的的html元素
34                 str1 = each.replace('&ldquo;', ' ')
35                 str2 = str1.replace('&hellip;', ' ')
36                 str3 = str2.replace('&rdquo;',' ')
37                 f.write(str3 + '\n')

 

【解決過程】

1. 再次確認其編碼格式,確實是utf-8;

2.此問題覺得很詭異的是,本身調用UTF-8去decode,但是解碼出錯卻提示的是GBK的,而不是UTF-8相關解碼出錯。

3.找了其他帖子,嘗試在解碼時添加ignore 屬性,但沒有解決。文中提供的第二種解釋,直覺不是這個原因。繼續找其他帖子。

https://www.crifan.com/unicodeencodeerror_gbk_codec_can_not_encode_character_in_position_illegal_multibyte_sequence/

4.又找到一個,

http://www.jb51.net/article/64816.htm

根據提示,在文件打開時添加 encoding='utf-8', 即,

    with open('E:\盜墓test22.txt', 'w',encoding='utf-8') as f:

問題解決。

 

 


【參考】

【總結】Python 2.x中常見字符編碼和解碼方面的錯誤及其解決辦法


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM