最近,用Python爬虫,去中文小说网站抓取下。发现,在写入文件的时候,出现UnicodeEncodeError,但是打印显示问题。
如这样:
traceback (most recent call last):
File "xioashuo.py", line 56, in <module>
f.write(chapter_name.encode('utf-8'))
UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 20: ordinal not in range(128)
解决办法:
f.write(u''.join(chapter_name).encode('utf-8'))
总结:
Python2.7默认ASCII编码,需转换为Unicode,进行读写操作。
说明:
环境:Python2.7、Windows10