首页 > 解决方案 > 使用 xpath 从 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()

关于我可能做错了什么的任何建议?谢谢!

标签: pythoncssxpathweb-scrapingscrapy

解决方案


您可以使用这个 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


推荐阅读