在非常大的HTML文件上使用BeautifulSoup - 内存错误?

时间:2015-07-03 07:49:41

标签: python html parsing beautifulsoup html-parsing

我通过一个项目 - 一个Facebook消息分析器来学习Python。我下载了我的数据,其中包含我所有消息的messages.htm文件。我试图编写一个程序来解析这个文件并输出数据(消息数,最常见的单词等)

但是,我的messages.htm文件是270MB。在shell中创建BeautifulSoup对象进行测试时,任何其他文件(全部<1MB)都可以正常工作。但我无法创建messages.htm的bs对象。这是错误:

>>> mf = open('messages.htm', encoding="utf8")
>>> ms = bs4.BeautifulSoup(mf)
Traceback (most recent call last):
  File "<pyshell#73>", line 1, in <module>
    ms = bs4.BeautifulSoup(mf)
  File "C:\Program Files (x86)\Python\lib\site-packages\bs4\__init__.py", line 161, in __init__
markup = markup.read()
  File "C:\Program Files (x86)\Python\lib\codecs.py", line 319, in decode
(result, consumed) = self._buffer_decode(data, self.errors, final)
MemoryError

所以我甚至无法开始使用这个文件。这是我第一次处理这样的事情而且我只是学习Python所以任何建议都会非常感激!

1 个答案:

答案 0 :(得分:1)

当您将此作为学习练习时,我不会给出太多代码。使用ElementTree's iterparse可能会更好,以便在解析时进行处理。就我所知,BeautifulSoup没有此功能。

为了帮助您入门:

import xml.etree.cElementTree as ET

with open('messages.htm') as source:

    # get an iterable
    context = ET.iterparse(source, events=("start", "end"))

    # turn it into an iterator
    context = iter(context)

    # get the root element
    event, root = context.next()

    for event, elem in context:
        # do something with elem

        # get rid of the elements after processing
        root.clear()

如果您已开始使用BeautifulSoup,您可以考虑将源HTML拆分为可管理的块,但是您需要小心保留线程消息结构并确保保持有效的HTML。