UnicodeEncodeError: ‘gbk‘ codec can‘t encode character ‘\xe7‘ in position 295: illegal multibyte seq
生活随笔
收集整理的這篇文章主要介紹了
UnicodeEncodeError: ‘gbk‘ codec can‘t encode character ‘\xe7‘ in position 295: illegal multibyte seq
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
解決UnicodeEncodeError: ‘gbk‘ codec can‘t encode character ‘\xe7‘ in position 295: illegal multibyte seq
錯誤代碼:
正確代碼:
with open("baidu.html",'w+',encoding="utf-8") as f:f.write(results.text)在抓取網頁上面的一些源代碼的時候,將uft-8的編碼寫入文檔,并輸出的時候,出現這了這個報錯,說gbk無法編碼\xbb
查找相關資料:
1.str轉bytes叫encode,bytes轉str叫decode
2.字符就是unicode字符,字符串就是unicode字符數組
原來,open()函數的默認編碼不是utf-8,修改編碼方式即可
write()函數涉及的問題,那就是它的參數必須是str,不能是bytes,也就是說f.write(result)中的result參數如果是bytes需要先decode成str(比如result.decode(‘utf-8’)),才能使用open()函數的encoding
總結
以上是生活随笔為你收集整理的UnicodeEncodeError: ‘gbk‘ codec can‘t encode character ‘\xe7‘ in position 295: illegal multibyte seq的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如何选择漏电保护器规格型号_老师傅告诉你
- 下一篇: ERRORS:*: (auth.E003