【问题标题】:Python HTML to Text File UnicodeDecodeError?Python HTML 到文本文件 UnicodeDecodeError?
【发布时间】: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


    【解决方案1】:

    您应该使用正确的编码解码从 urllib 获取的内容,例如 utf-8 latin1 取决于您获取的页面。

    检测内容编码的方式多种多样。来自 html 中的标题或元数据。我想用一个编码检测模块,忘记名字了,你可以google一下。

    正确解码后,您可以在写入文件之前将其编码为您喜欢的任何编码

    =======================================

    这是使用chardet的示例

    import urllib
    import chardet
    
    
    def main():
        page = urllib.urlopen('http://bbc.com')
        content = page.read()
    
        # detect the encoding
        try:
            encoding = chardet.detect(content)['encoding']
        except:
            # use utf-8 as default encoding
            encoding = 'utf-8'
    
        # decode the content into unicode
        content = content.decode(encoding)
    
        # write to file
        with open('test.txt', 'wb') as f:
            f.write(content.encode('utf-8'))
    

    【讨论】:

    • 你能举个例子吗?
    • @ChrisNguyen 我当时不太方便,这里我添加我的例子
    • 哦,好吧,我知道编码是如何工作的...您必须使用其原始编码格式/方法对其进行解码?...唯一的方法是使用外部库来检测编码?或者有没有没有外部模块的方法?
    • 我该如何使用 chardet?我下载了 chardet.tar.gz 并运行了“python setup.py install”,但我这里没有 setuptools……无论如何要解决这个问题?
    • 关注this,setuptools是安装第三方模块的基础组件
    【解决方案2】:

    您必须知道远程网页使用的编码。有很多方法可以实现这一点,但最简单的方法是使用 Python-Requests 库而不是 urllib。 Requests 返回预解码的 Unicode 对象。

    然后您可以使用编码文件包装器来自动对您编写的每个字符进行编码。

    import requests
    import io
    
    def download(self, url, name="WebPage.txt"):
        ## Saves only the text to file
        req = requests.get(url)
        content = req.text # Returns a Unicode object decoded using the server's header
        with io.open(name, 'w', encoding="utf-8") as w: # Everything written to w is encoded to UTF-8
            w.write( HTT.html2text( content) )
    
        print "Saved"
    

    【讨论】:

    • 请求外部模块吗?如果是这样,我该如何获得它?.. 默认 python 库中有什么可以做到这一点吗?
    猜你喜欢
    • 2016-04-17
    • 2020-10-07
    • 2016-02-08
    • 1970-01-01
    • 2019-04-10
    • 1970-01-01
    • 1970-01-01
    • 2013-09-15
    • 2012-09-26
    相关资源
    最近更新 更多