控制台輸出問題

來源:互聯網
上載者:User

標籤:char   tail   文章   ror   pos   預設   can   出現   函數   

在控制台使用print函數列印爬蟲爬取的中文文章時,出現錯誤

UnicodeEncodeError: ‘gbk‘ codec can‘t encode character ‘\U0001f602‘ in position。。。

文章採用utf8編碼的,錯誤資訊卻顯示gbk無法編碼字元‘\U0001f602‘

說明utf8的文章在列印過程中被轉成gbk,而gbk顯然無法編碼unicode的某些字元。

解決方案有兩個:

①修改標準輸出資料流的編碼方式:

import io

import sys

sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding=‘gb18030‘)

或者

sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding=‘utf8‘)

 

②還有一種一勞永逸的方法——修改控制台編碼:

命令列輸入  chcp

輸出顯示:活動字碼頁: 936

表示當前的編碼是預設的gbk

修改編碼:

命令列輸入  chcp 65001

表示轉換成utf8

字型選擇Lucida Console

然後可以成功print爬取的中文文章
---------------------
原文連結:81219186

控制台輸出問題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.