使用requests库下载txt文件的时候报错:
Traceback (most recent call last):
File "D:/ALL_workspace/pycharm/Code/TaiwanSpider/text.py", line 8, in <module>
f.write(r.text)
UnicodeEncodeError: 'gbk' codec can't encode character '\ufeff' in position 0: illegal multibyte sequence
我的代码如下:
# -*- coding:utf-8-*-
import requests
url = "http://www.gutenberg.org/files/1692/1692-0.txt"
r = requests.get(url)
r.encoding = 'utf-8'
f = open('./words.txt',"w")
f.write(r.text)
f.close()
解决方案:
更改了部分代码,就Ok了。
f.encoding = "utf-8-sig"