【问题标题】:Using BeautifulSoup on very large HTML file - memory error?在非常大的 HTML 文件上使用 BeautifulSoup - 内存错误?
【发布时间】:2015-07-03 07:49:41
【问题描述】:

我正在通过一个项目学习 Python——Facebook 消息分析器。我下载了我的数据,其中包括我所有消息的 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,所以任何建议都将不胜感激!

【问题讨论】:

    标签: python html parsing beautifulsoup html-parsing


    【解决方案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。

    【讨论】:

    • 谢谢!我没有设置 BeautifulSoup,我刚刚读到人们称赞它并想我会尝试,但显然我现在必须考虑其他选择。我现在会检查 ElementTree 并尝试您的建议,再次感谢。
    猜你喜欢
    • 2020-08-13
    • 1970-01-01
    • 2011-11-11
    • 1970-01-01
    • 2013-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-27
    相关资源
    最近更新 更多