将 Xpath 与 lxml etree 一起使用时,列表无法序列化错误

Val*_*les 4 xpath lxml python-2.7

我试图在 XML 文档中搜索一个字符串,然后打印出包含该字符串的整个元素或多个元素。到目前为止,这是我的代码:

post = open('postf.txt', 'r')
postf = str(post.read())

root = etree.fromstring(postf)

e = root.xpath('//article[contains(text(), "stuff")]')

print etree.tostring(e, pretty_print=True)
Run Code Online (Sandbox Code Playgroud)

这是正在从 postf.txt 中搜索的 XML

<stuff>

<article date="2014-05-18 17:14:44" title="Some stuff">More testing
debug
[done]
<tags>Hello and stuff
</tags></article>

</stuff>
Run Code Online (Sandbox Code Playgroud)

最后,这是我的错误:

  File "cliassis-1.2.py", line 107, in command
    print etree.tostring(e, pretty_print=True)
  File "lxml.etree.pyx", line 3165, in lxml.etree.tostring (src\lxml\lxml.etree.c:69414)
TypeError: Type 'list' cannot be serialized.
Run Code Online (Sandbox Code Playgroud)

我想要做的是搜索包含我搜索的字符串的所有元素,然后打印出标签。所以如果我有测试和东西,我搜索“测试”,我希望它打印出“测试和东西”

unu*_*tbu 5

articles = root.xpath('//article[contains(text(), "stuff")]')

for article in articles:
    print etree.tostring(article, pretty_print=True)
Run Code Online (Sandbox Code Playgroud)

root.xpath返回一个 Python 列表。e列表也是如此。etree.tostring将 lxml 转换_Elements为字符串;它不会将列表转换_Elements为字符串。所以使用 a将列表内部for-loop打印_Elements为字符串。