繁体   English   中英

Python HTML到文本文件UnicodeDecodeError?

[英]Python HTML to Text File UnicodeDecodeError?

因此,我正在编写一个程序来使用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!"

我必须缺少其他方法或编码...请帮助!

Side Quest:有时我必须将其写入一个文件名,其中包含不受支持的字符,例如“ G \\ u00e9za Teleki” +“。txt” 如何过滤掉这些字符?

注意:

  • 此函数存储在一个类中(提示“ self”)。
  • 使用python2.7
  • 不想使用BeautfiulSoup
  • Windows 8 64位

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

检测内容编码的方式多种多样。 来自标头或html中的meta。 我想使用一个编码检测模块,但忘记了名称,可以用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'))

您必须知道远程网页使用的编码。 有很多方法可以实现这一点,但是最简单的方法是使用Python-Requests库而不是urllib。 请求返回预解码的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"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM