我使用python爬行了一些网页,并将读取的行保存到一个新文件中。
f = open(docId + ".html", "w+")
with urllib.request.urlopen('http://stackoverflow.com') as u:
s = u.read()
f.write(str(s))
但是当我打开保存的文件时,我会看到许多字符串,比如\xe2\x86\x90,它最初是原始页面中的箭头符号。它似乎是一个符号的UTF-8代码,但我如何将代码转换回符号?
发布于 2015-01-23 14:04:08
您的代码坏了:u.read()
返回bytes
对象。str(bytes_object)
返回对象的字符串表示(字节文本的样子) --您不希望它出现在这里:
>>> str(b'\xe2\x86\x90')
"b'\\xe2\\x86\\x90'"
或者按如下方式将字节保存在磁盘上:
import urllib.request
urllib.request.urlretrieve('http://stackoverflow.com', 'so.html')
或者以二进制模式打开文件:'wb'
并手动保存:
import shutil
from urllib.request import urlopen
with urlopen('http://stackoverflow.com') as u, open('so.html', 'wb') as file:
shutil.copyfileobj(u, file)
或将字节转换为Unicode,并使用任何您喜欢的编码将它们保存到磁盘。
import io
import shutil
from urllib.request import urlopen
with urlopen('http://stackoverflow.com') as u, \
open('so.html', 'w', encoding='utf-8', newline='') as file, \
io.TextIOWrapper(u, encoding=u.headers.get_content_charset('utf-8'), newline='') as t:
shutil.copyfileobj(t, file)
发布于 2015-01-23 07:38:14
尝试:
import urllib2, io
with io.open("test.html", "w", encoding='utf8') as fout:
s = urllib2.urlopen('http://stackoverflow.com').read()
s = s.decode('utf8', 'ignore') # or s.decode('utf8', 'replace')
fout.write(s)
https://stackoverflow.com/questions/28104377
复制相似问题