2017-02-28 6 views
2

私はPythonの初心者です。エラー:UnicodeEncodeError: 'gbk'コーデックが文字をエンコードできません

from bs4 import BeautifulSoup 
import requests 

url = "http://www.google.com" 
response = requests.get(url) 
soup = BeautifulSoup(response.text, "html.parser") 
links = soup.find_all("a") 
for link in links: 
    print(link.text) 

Windowsのpowershellでこの.pyファイルを実行すると、print(link.text)によって次のエラーが発生します。

error: UnicodeEncodeError: 'gbk' codec can't encode charactor '\xbb' in position 5: 
illegal multibyte sequence. 

は、私はエラーがいくつかの漢字によって引き起こされる知っている、と私は「デコード」を使用するか、「無視する」必要があるようです思えるが、私は自分のコードを修正する方法がわかりません。助けてください!ありがとう!

答えて

0

あなたがそれらの特殊文字を表示したくない場合は:あなたはutf8内の文字列をエンコードすることができます

print(link.text.encode(errors="ignore")) 
0


次の方法でそれらを無視することができます。

for link in links: 
    print(link.text.encode('utf8')) 

しかし、より良い方法がある:

response = requests.get(url) 
soup = BeautifulSoup(response.text.encode("utf8"), "html.parser") 

あなたが直面している問題についての詳細を理解するには、このstackoverflow answerをご覧ください。

関連する問題