【发布时间】:2015-06-27 13:30:47
【问题描述】:
我正在尝试将来自 Google 的 HTML 代码字符串写入 Python 3.4 中的文件
#coding=utf-8
try:
from urllib.request import Request, urlopen # Python 3
except:
from urllib2 import Request, urlopen # Python 2
useragent = 'Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.0'
#Generate URL
url = 'https://www.google.com.tw/search?q='
query = str(input('Google It! :'))
full_url = url+query
#Request Data
data = Request(full_url)
data.add_header('User-Agent', useragent)
dataRequested = urlopen(data).read()
dataRequested = str(dataRequested.decode('utf-8'))
print(dataRequested)
#Write Data Into File
file = open('Google - '+query+'.html', 'w')
file.write(dataRequested)
它可以正确打印字符串, 但是当它写入文件时, 它会显示
file.write(dataRequested)
UnicodeEncodeError: 'cp950' codec can't encode character '\u200e' in position 97658: illegal multibyte sequence
我试图改变解码方式,但它不起作用。 我也尝试替换\u200e,但它会出现更多的编码字符错误。
【问题讨论】:
标签: python python-3.x unicode unicode-string