问题描述
我一直在使用lxml和formalchemy构建sqlalchemy的脚手架库,但我很难让它们很好地发挥作用.具体来说,formalchemy.FieldSet.render()
返回没有根标记的html片段,而且我似乎无法弄清楚如何使lxml将其解析为可以包含在元素树中的内容:
I've been building a scaffolding library for sqlalchemy using lxml and formalchemy, and I'm having a hard time getting them to play nicely. specifically, formalchemy.FieldSet.render()
returns a fragment of html with no root tag, and I cannot seem to figure out how to get lxml to parse it into something that can be included into an element tree:
我能得到什么:
>>> 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>]
推荐答案
要解析HTML,您要使用lxml.html
而不是lxml.etree
.
For parsing HTML you want to use lxml.html
, not lxml.etree
.
如果您想要片段列表而不是将片段包装在div
中,则可以按照fragments_fromstring(string) rel ="noreferrer">此处.
If you want a list of fragments instead of wrapping them in a div
you can use fragments_fromstring(string)
as described here.
这篇关于没有根标记时使用lxml进行html解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!