小编Val*_*les的帖子

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

我试图在 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)

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

xpath lxml python-2.7

4
推荐指数
1
解决办法
1万
查看次数

标签 统计

lxml ×1

python-2.7 ×1

xpath ×1