【问题标题】:List can not be serialized error when using Xpath with lxml etree将 Xpath 与 lxml etree 一起使用时列表无法序列化错误
【发布时间】:2014-05-18 22:52:59
【问题描述】:

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

这是从 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>

最后,这是我的错误:

  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.

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

【问题讨论】:

    标签: python-2.7 xpath lxml


    【解决方案1】:
    articles = root.xpath('//article[contains(text(), "stuff")]')
    
    for article in articles:
        print etree.tostring(article, pretty_print=True)
    

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

    【讨论】:

    • 这很好用,解释让我明白为什么它不起作用。谢谢你。 :D
    【解决方案2】:

    你也可以像这样使用内置的join函数。

    e = root.xpath('//article[contains(text(), "stuff")]')
    joined_string = "".join(e)//list to string conversion
    print joined_string
    

    【讨论】:

      【解决方案3】:

      这是一个 executableworking 解决方案,它也使用join(但正确) - 使用列表理解:

      from lxml import etree
      
      root = etree.fromstring('''<stuff>
      
      <article date="2014-05-18 17:14:44" title="Some stuff">stuff in text
      <tags>Hello and stuff</tags>
      </article>
      
      <article date="whatever" title="Some stuff">no s_t_u_f_f in text
      <tags>Hello and stuff</tags>
      </article>
      
      <article date="whatever" title="whatever">More stuff in text
      <tags>Hello and stuff</tags>
      </article>
      
      </stuff>''')
      articles = root.xpath('//article[contains(text(), "stuff")]')
      
      print("".join([etree.tostring(article, encoding="unicode", pretty_print=True) for article in articles]))
      

      (对于 encoding="unicode" 参见例如http://makble.com/python-why-lxml-etree-tostring-method-returns-bytes

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-08-17
        • 2013-04-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-29
        • 1970-01-01
        相关资源
        最近更新 更多