[英]Python, UnicodeEncodeError: 'charmap' codec can't encode characters in position
I want to write the HTML of a website to the file I created, tough I decode to utf-8 but still it puts up a error like this, I use print(data1)
and the html is printed properlyand I am using python 3.5.0 我想将网站的HTML写到我创建的文件中,很难解码为utf-8,但仍然会出现这样的错误,我使用print(data1)
,并且html正确打印,并且我正在使用python 3.5。 0
import re
import urllib.request
city = input("city name")
url = "http://www.weather-forecast.com/locations/"+city+"/forecasts/latest"
data = urllib.request.urlopen(url).read()
data1 = data.decode("utf-8")
f = open("C:\\Users\\Gopal\\Desktop\\test\\scrape.txt","w")
f.write(data1)
You've opened a file with the default system encoding : 您已使用默认系统编码打开了一个文件:
f = open("C:\\Users\\Gopal\\Desktop\\test\\scrape.txt", "w")
You need to specify your encoding explicitly: 您需要明确指定编码:
f = open("C:\\Users\\Gopal\\Desktop\\test\\scrape.txt", "w", encoding='utf8')
See the open()
function documentation : 请参阅open()
函数文档 :
In text mode, if encoding is not specified the encoding used is platform dependent:
locale.getpreferredencoding(False)
is called to get the current locale encoding. 在文本模式下,如果未指定编码,则使用的编码取决于平台:locale.getpreferredencoding(False)
以获取当前的语言环境编码。
On your system, the default is a codec that cannot handle your data. 在您的系统上,默认值为无法处理数据的编解码器。
f = open("C:\\Users\\Gopal\\Desktop\\test\\scrape.txt","w",encoding='utf8')
f.write(data1)
This should work, it did for me 这应该工作,对我有用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.