python写文件时遇到UnicodeEncodeError: 'gbk' codec can't encode character...时处理办法

网页上爬取内容后要写入文件保存,在写入时出错了。

写文件时遇到“UnicodeEncodeError: 'gbk' codec can't encode character '\uf0fc' in position 147: illegal multibyte sequence”错误

网上查找处理办法,经过实测=后以下方法可行:

在打开文件时定义文件编码为UTF-8,出现错误时忽略,即:

f = open('tt.csv', 'w', encoding="utf-8", errors="ignore")

f.writelines("爬取的内容")

f.close()

或:

with open(hid+".html",'w',encoding="utf-8",errors="ignore") as f:

  f.writelines("爬取的内容")

上一篇:MySQL登录提示:host *.*.*.* is blocked because of many connection errors


下一篇:Centos6.5 克隆之后,重启网卡报错 No suitable device found: no device found for connection 'System eth0