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

问题描述 投票:2回答:2

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

但是,我的messages.htm文件为270MB。在外壳程序中创建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,所以任何建议都将不胜感激!

python html parsing beautifulsoup html-parsing
2个回答
2
投票

当您将其用作学习练习时,我不会提供太多代码。最好使用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。

© www.soinside.com 2019 - 2024. All rights reserved.