[問題] 中文編碼

作者: IsMe1086 (大頭)   2015-12-19 09:44:46
小弟是剛接觸PYTHON的新手 正在練習抓網頁的寫法
已經爬版和GOOGLE 還是找不到方法
先附上程式碼
import urllib
import urllib.request
thisurl = "http://www.cna.com.tw/"
handle = urllib.request.urlopen(thisurl)
html_gunk = handle.read().decode(encoding="utf-8",errors="ignore")
f = open('t.txt','w')
f.write(html_gunk)
然後出現錯誤訊息
Traceback (most recent call last):
File "openurl - wf.py", line 15, in <module>
f.write(html_gunk)
UnicodeEncodeError: 'cp950' codec can't encode character '\xf1' in position
15378: illegal multibyte sequence
麻煩高手指點迷津
作者: alibuda174 (阿哩不達)   2015-12-19 09:53:00
open時也指定編碼utf-8試試
作者: IsMe1086 (大頭)   2015-12-19 10:22:00
可以了!感謝你~~~

Links booklink

Contact Us: admin [ a t ] ucptt.com