0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PythonクローリングにおけるUnicodeEncodeErrorの対応

Last updated at Posted at 2019-09-09

Pythonでクローリングするにあたり、
requestsを使用したときに少しハマったので備忘録として記録。

エラー内容

# test.py
import requests

r = requests.get('今回のターゲットURL')
print(r.text)

このファイルを保存し、下記コマンドで実行してhtmlファイルに書き出す。
$ python test.py > dp.html

すると下記のエラーが発生する。
UnicodeEncodeError: 'cp932' codec can't encode character '\xa9' in position 40629: illegal multibyte sequence

原因

なにがダメなのかググった結果、
どうやら著作権の©(\xa9)が悪さしているとのこと。

対策

ということで、こいつを無理やり置き換えて出力すればうまくいくのではと思い下記の通り変更

# test.py
import requests

r = requests.get('https://gihyo.jp/dp')
print(r.text.replace('\xa9',''))

結果

うまくいった。
荒業かもしれないが、正直クローリングには関係ないところだったので、置き換えても何の問題もない。

ちなみに、htmlファイルに書き出さず、そのままprintするだけなら置き換えなくてもエラーが発生しない。
htmlファイルに書き出す際、文字コードを置き換えているみたいで、その際にエラーになってしまうみたい。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?