当没有根标签时用hxml解析html

时间:2012-04-15 20:26:18

标签: python lxml formalchemy

我一直在使用lxml和formalchemy为sqlalchemy构建一个脚手架库,我很难让他们玩得很好。具体来说,formalchemy.FieldSet.render()返回一个没有root标签的html片段,我似乎无法弄清楚如何让lxml将其解析成可以包含在元素树中的东西:

我得到了什么:

>>> lxml.etree.fromstring(formalchemy.FieldSet(toyschema.User(), session).render())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "lxml.etree.pyx", line 2743, in lxml.etree.fromstring (src/lxml/lxml.etree.c:52665)
  File "parser.pxi", line 1573, in lxml.etree._parseMemoryDocument (src/lxml/lxml.etree.c:79932)
  File "parser.pxi", line 1445, in lxml.etree._parseDoc (src/lxml/lxml.etree.c:78709)
  File "parser.pxi", line 920, in lxml.etree._BaseParser._parseUnicodeDoc (src/lxml/lxml.etree.c:75083)
  File "parser.pxi", line 564, in lxml.etree._ParserContext._handleParseResultDoc (src/lxml/lxml.etree.c:71739)
  File "parser.pxi", line 645, in lxml.etree._handleParseResult (src/lxml/lxml.etree.c:72614)
  File "parser.pxi", line 585, in lxml.etree._raiseParseError (src/lxml/lxml.etree.c:71955)
lxml.etree.XMLSyntaxError: Extra content at the end of the document, line 8, column 1

我想要的:

>>> ?????(formalchemy.FieldSet(toyschema.User(), session).render())
[<Element div at 0x1e48e10>, <Element script at 0x1e48cd0>, <Element div at 0x1e48730>, <Element div at 0x1ea1e60>]

我的原油解决方案:

>>> lxml.etree.fromstring('<root>%s</root>' % formalchemy.FieldSet(toyschema.User(), session).render()).getchildren()
[<Element div at 0x1e48e10>, <Element script at 0x1e48cd0>, <Element div at 0x1e48730>, <Element div at 0x1ea1e60>]

1 个答案:

答案 0 :(得分:6)

要解析HTML,您要使用lxml.html,而不是lxml.etree

如果你想要一个片段列表而不是将它们包裹在div中,你可以使用here所述的fragments_fromstring(string)