【问题标题】:BeautifulSoup returns spaced text after parsingBeautifulSoup 解析后返回间隔文本
【发布时间】:2019-07-22 07:58:51
【问题描述】:

我正在抓取一个本地 html 文档。但是,当我用漂亮的汤解析它时,它会以一种无法解析的丑陋(如下图所示)格式返回 html。

我使用的简单代码是:

path = 'alerts/myfile.htm'
file = open(os.path.abspath(path))
parser = BeautifulSoup(file,'html.parser')
file.close()

这件事快把我逼疯了。你有过同样的问题吗? 谢谢

【问题讨论】:

  • 可以提供html文件吗?
  • 不幸的是我不允许:(

标签: python html parsing web-scraping beautifulsoup


【解决方案1】:

在我看来,源文件编码存在问题。

加载文档时,BeautifulSoup 使用名为 Unicode Dammit 的子库将其转换为 UTF-8。

可能是您的文件已使用不同的编码保存,并且在转换中发生了某种错误。

由于我手头没有您的 html,我建议您调查一下您的文件是 ASCII 还是 Unicode 或任何其他编码,然后使用以下命令解析文件:

encoding = <your encoding here> (example "iso-8859-8")
parser = BeautifulSoup(file,'html.parser', from_encoding=encoding)

其他编码选项可以找到here

问候

更新

也可以试试:

parser = BeautifulSoup(file,'html.parser', from_encoding='utf-8')

【讨论】:

    【解决方案2】:

    看起来原始文件是 UTF-16 格式。

    无论出于何种原因,BeautifulSoup(..., from_encoding='utf-16le') 不理解这种情况,但您可以通过在将文件传递给 BS 之前手动读取和解码文件来解决此问题。

    请参阅下面的脚本,其中我创建了一个 UTF-16LE 的 HTML 文件,转储其内容,尝试将其直接传递到 BS4,最后使用上述解决方法。

    $ echo '<html><div>hello</div></html>' | iconv -f utf-8 -t utf-16le > y.html
    $ file y.html
    $ xxd y.html
    00000000: 3c00 6800 7400 6d00 6c00 3e00 3c00 6400  <.h.t.m.l.>.<.d.
    00000010: 6900 7600 3e00 6800 6500 6c00 6c00 6f00  i.v.>.h.e.l.l.o.
    00000020: 3c00 2f00 6400 6900 7600 3e00 3c00 2f00  <./.d.i.v.>.<./.
    00000030: 6800 7400 6d00 6c00 3e00 0a00            h.t.m.l.>...
    $ python
    >>> import bs4
    >>> s = bs4.BeautifulSoup(open('y.html'))
    &lt;html&gt;&lt;div&gt;hello&lt;/div&gt;&lt;/html&gt;
    >>> s = bs4.BeautifulSoup(open('y.html'), from_encoding='utf-16le')
    &lt;html&gt;&lt;div&gt;hello&lt;/div&gt;&lt;/html&gt;
    >>> s = bs4.BeautifulSoup(open('y.html'), 'html.parser', from_encoding='utf-16le')
    &lt;html&gt;&lt;div&gt;hello&lt;/div&gt;&lt;/html&gt;
    >>> d = open('y.html', 'rb').read().decode('utf-16le')
    >>> d
    '<html><div>hello</div></html>\n'
    >>> s = bs4.BeautifulSoup(d)
    >>> s
    <html><div>hello</div></html>
    >>>
    

    【讨论】:

      【解决方案3】:

      我想我解决了:我的文件采用 UCL-2 编码。我所做的是:

       path = 'alerts/myfile.htm'
      file = open(os.path.abspath(path),'rb')
      parser = BeautifulSoup(file.read().decode('utf-8'),'html.parser')
      file.close()
      parser.find('table', attrs = {'class':'MsoNormalTable'})
      

      现在是输出:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-01-30
        • 2015-11-02
        • 1970-01-01
        • 2021-01-10
        • 2021-01-18
        • 2012-02-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多