使用xpath从span中提取值

2024-05-23 20:50:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从span类中获得如下价格: (来源:https://www.leadhome.co.za/property/die-hoewes/centurion/lh-114269/lovely-3-bedroom-unit-for-sale-in-die-hoewes

<div class="col-sm-4">
  <div>
     <strong>Levy</strong>
     <span class="pull-right">R2,343</span>

我尝试用以下方式执行此操作,但它不会返回任何内容:

levy = response.xpath('//span[@class="pull-right"][contains(text(), "Levy")]/text()').get()

有没有关于我可能做错了什么的建议? 谢谢大家!


Tags: texthttpsrightdivwww来源价格pull
2条回答

可以使用以下XPath-1.0表达式:

//span[@class="pull-right" and contains(../strong/text(), "Levy")]/text()

或者,整体而言

levy = response.xpath('//span[@class="pull-right" and contains(../strong/text(), "Levy")]/text()').get()

另一种方法是匹配<div>(如果它只有一个子项<span>):

//div[span/@class="pull-right" and contains(strong, "Levy")]/span/text()

在这两种情况下,输出都是:

R2,343

在我看来,contains语句不起作用,因为xpath从span元素开始。通过从父div标记开始,您可以确认强标记和span都与您期望的匹配

//div/strong[contains(text(), "Levy")]/following-sibling::span[@class="pull-right"]

相关问题 更多 >