python - 使用 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()
关于我可能做错了什么的任何建议?谢谢!
解决方案
您可以使用这个 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
推荐阅读
- sql - SQL 度量行到日期列-
- php - 在 Laravel 中正确访问 API
- reactjs - 此警告的可能原因和解决方案
- nativescript - 将 PWA 版本的 Google Apps 嵌入到 Nativescript 应用程序中
- c++ - 需要有关代码堵塞问题“PARENTING PARTNERSHIP”的帮助
- jdbc - 在 REDHAT JBoss EAP 7.0 中为 Mariadb 配置 XADatasource
- couchbase - Couchbase 查询 - 将值从一个(子)查询传递到另一个查询作为输入并获取值
- html - 左右对齐同一行上的两个 div
- python - 为什么 Atom IDE 控制台和终端上有不同版本的 Python?
- html - 表单未提交 POST