使用Python解析非常大的HTML文件(ElementTree?)

时间:2015-07-04 21:19:57

标签: python html parsing html-parsing elementtree

I asked about using BeautifulSoup to parse a very large (270MB) HTML file and getting a memory error andwas pointed toward ElementTree as a solution.

我试图使用他们的事件驱动解析documented here。使用较小的设置文件进行测试工作正常:

>>> settings = open('S:\\Documents\\FacebookData\\html\\settings.htm')
>>> for event, element in ET.iterparse(settings, events=("start", "end")):
    print("%5s, %4s, %s" % (event, element.tag, element.text))

成功打印出元素。但是,使用相同的代码与'messages.htm'而不是'settings.htm'只是为了看看它是否在开始实际编码过程之前有效,这就是结果:

Traceback (most recent call last):
  File "<pyshell#16>", line 1, in <module>
    for event, element in ET.iterparse(source, events=("start", "end")):
  File "C:\Program Files (x86)\Python\lib\xml\etree\ElementTree.py", line 1294, in __next__
for event in self._parser.read_events():
  File "C:\Program Files (x86)\Python\lib\xml\etree\ElementTree.py", line 1277, in read_events
raise event
  File "C:\Program Files (x86)\Python\lib\xml\etree\ElementTree.py", line 1235, in feed
self._parser.feed(data)
  File "<string>", line None
xml.etree.ElementTree.ParseError: not well-formed (invalid token): line 1, column 6

我想知道这是否因为ET更适合解析XML文档?如果是这种情况,并且没有解决方法,那么我就回到原点。任何有关如何解析此文件的建议,以及如何在此过程中进行调试都将非常感谢!

2 个答案:

答案 0 :(得分:0)

解析HTML或XML的一个很好的解决方案是lxmlxpath

使用xpath:

from lxml import etree
data = open('result.html','r').read()
doc = etree.HTML(data)

for tr in doc.xpath('//table/tr[@class="trmenu1"]'):
    print tr.xpath('./td/text()')

答案 1 :(得分:0)

Html不是一个完美的XML。 这就是为什么在某些情况下,您使用HTMLParser而不是ElementTree来解析html文件。

最好的关注 灵光