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)
4

2 回答 2

3

您已经使用默认系统编码打开了一个文件:

f = open("C:\\Users\\Gopal\\Desktop\\test\\scrape.txt", "w")

您需要明确指定您的编码:

f = open("C:\\Users\\Gopal\\Desktop\\test\\scrape.txt", "w", encoding='utf8')

请参阅open()功能文档

在文本模式下,如果未指定编码,则使用的编码取决于平台:locale.getpreferredencoding(False)调用以获取当前的语言环境编码。

在您的系统上,默认设置是无法处理您的数据的编解码器。

于 2015-11-02T23:49:42.160 回答
0
f = open("C:\\Users\\Gopal\\Desktop\\test\\scrape.txt","w",encoding='utf8')


f.write(data1)

这应该有效,它对我有用

于 2018-09-16T18:55:47.593 回答