【问题标题】:lxml xpath to return one list item for all descendants of nodelxml xpath为节点的所有后代返回一个列表项
【发布时间】:2017-11-10 16:04:01
【问题描述】:

xml:

<div class="nsm-brief-primary-title-group">
        <a class="nsm-brief-action-link" href="/Mobile/Search/Title/1.10.1.511937"><span class="nsm-short-item nsm-e135"><span class="nsm-hit-text">Airplanes</span> take off and land</span></a>
    </div>

例如这段代码:

titles = tree.xpath('//div[@class="nsm-brief-primary-title-group"]/descendant::*/text()')
print 'titles: ', titles

返回一个列表:

titles:  ['Airplanes', ' take off and land']

如何使具有该类名的 div 的后代中的任何文本显示为数组中的单个项目?

titles:  ['Airplanes take off and land']

【问题讨论】:

    标签: python html xml xpath lxml


    【解决方案1】:

    要将元素的所有后代文本节点作为单个字符串获取,您可以使用 XPath string() 函数将元素转换为字符串:

    title = tree.xpath('string(//div[@class="nsm-brief-primary-title-group"]/a)')
    

    如果div 中可以有多个a 元素,并且您希望每个元素都有一个字符串,那么您需要在单个a 元素上应用string() 函数:

    titles = [a.xpath('string()') for a in 
                tree.xpath('//div[@class="nsm-brief-primary-title-group"]/a')]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-04
      • 2011-04-03
      • 2012-12-03
      相关资源
      最近更新 更多