【发布时间】:2015-11-28 01:03:23
【问题描述】:
所以我正在编写一个程序来使用 urllib 读取网页,然后使用“html2text”将基本文本写入文件。但是,从 urllib.read() 给出的原始内容具有各种字符,因此会不断引发 UnicodeDecodeError。
当然,我在 Google 上搜索了 3 个小时,得到了很多答案,例如使用 HTMLParser 或 reload(sys),使用 pdfkit 或 BeautifulSoup 等外部模块,当然还有 .encode/.decode。
重新加载 sys,然后执行 sys.setdefaultencoding("utf-8") 可以获得所需的结果,但之后 IDLE 和程序变得无响应。
我用“utf-8”和“ascii”尝试了 .encode/.decode 的所有变体,带有“replace”、“ignore”等参数。出于某种原因,它每次都会引发相同的错误,无论我在编码/解码中提供的参数。
def download(self, url, name="WebPage.txt"):
## Saves only the text to file
page = urllib.urlopen(url)
content = page.read()
with open(name, 'wb') as w:
HP_inst = HTMLParser.HTMLParser()
content = content.encode('ascii', 'xmlcharrefreplace')
if True:
#w.write(HTT.html2text( (HP_inst.unescape( content ) ).encode('utf-8') ) )
w.write( HTT.html2text( content) )#.decode('ascii', 'ignore') ))
w.close()
print "Saved!"
必须有另一种方法或我缺少的编码...请帮助!
支线任务:有时我必须将其写入名称中包含不受支持的字符的文件,例如 "G\u00e9za Teleki"+".txt"。如何过滤掉这些字符?
注意:
- 此函数存储在一个类中(提示“self”)。
- 使用python2.7
- 不想用 BeautfiulSoup
- Windows 8 64 位
【问题讨论】:
标签: python html python-2.7 unicode urllib