【问题标题】:Search for specific text in XML tree and extract text in next node在 XML 树中搜索特定文本并在下一个节点中提取文本
【发布时间】:2021-02-12 21:40:19
【问题描述】:

试图从www.currys.co.uk 那里获取智能手表的重量。该网站并未对所有产品采用相同的结构,因此为了获得每种产品的权重,我尝试使用 xpath 进行关键字搜索:

//text()[contains(.,'Weight')]

我可以得到文字“重量”,但我想得到的是下面node那个contains重量的实际值:

<tbody>
 <tr>
   <th scope = "row">Weight</th>
   <td> 26.7 g</td>
 <tr>
<body>

我正在寻找的是获取文本26.7 g。我尝试使用以下方法,但它似乎不起作用:

//text()[contains(.,'Weight')]//td

有什么建议吗?提前致谢。

【问题讨论】:

    标签: xml web-scraping xpath scrapy contains


    【解决方案1】:

    你可以使用following-sibling::td:

    from lxml import etree
    
    
    txt = '''<tbody>
     <tr>
       <th scope = "row">Weight</th>
       <td> 26.7 g</td>
     </tr>
    </tbody>'''
    
    root = etree.fromstring(txt)
    
    for td in root.xpath('//th[contains(., "Weight")]/following-sibling::td'):
        print(td.text)
    

    打印:

     26.7 g
    

    【讨论】:

    • 工作出色。谢谢你。并且只是为了将来参考,为了获得前一个兄弟,我只是将上面的代码更改为“/preceding-sibling::td”?
    • @sophods 不幸的是,XPATH 不支持搜索先前元素的函数。这是 CSS/Xpath 备忘单:devhints.io/xpathlxml 中有 .getparent() 函数 - 从那里你可以搜索所有兄弟姐妹。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-01
    相关资源
    最近更新 更多