html - 使用 XPath 从表中获取元素
问题描述
我正在尝试从该网站获取信息 https://www.realtypro.co.za/property_detail.php?ref=1736
我有这张表,我想从中获取卧室的数量
<div class="panel panel-primary">
<div class="panel-heading">Property Details</div>
<div class="panel-body">
<table width="100%" cellpadding="0" cellspacing="0" border="0" class="table table-striped table-condensed table-tweak">
<tbody><tr>
<td class="xh-highlight">3</td><td style="width: 140px" class="">Bedrooms</td>
</tr>
<tr>
<td>Bathrooms</td>
<td>3</td>
</tr>
我正在使用这个 xpath 表达式:
bedrooms = response.xpath("//div[@class='panel panel-primary']/div[@class='panel-body']/table[@class='table table-striped table-condensed table-tweak']/tbody/tr[1]/td[2]/text()").extract_first()
但是,我只得到“无”作为输出。
我尝试了几种组合,但我只得到 None 作为输出。关于我做错了什么有什么建议吗?
提前致谢!
解决方案
我会使用 bs4 4.7.1。您可以在其中搜索具有文本:contains
的单元格,然后获取相邻的兄弟。您可以添加测试以进行错误处理。不如长 xpath 脆弱。td
"Bedrooms"
td
is None
import requests
from bs4 import BeautifulSoup as bs
r = requests.get('https://www.realtypro.co.za/property_detail.php?ref=1736')
soup = bs(r.content, 'lxml')
print(int(soup.select_one('td:contains(Bedrooms) + td').text)
如果位置是固定的,你可以使用
.table-tweak td + td
推荐阅读
- android - 如何在Android中按顺序(一个接一个)运行两个或多个动画?
- css - 托管动态内容的动画模板
- c# - 加载 XML 文件并转换为字符串
- python - 为什么 Python 脚本的第二行会影响 pip 的安装方式?
- angularjs - 删除浏览器数据后,ngstorage 的 $localStorage 仍可在 Angular 中使用
- java - Java泛型如何避免接口不能用不同的参数多次实现
- pentaho - 创建数据库源 - 定义连接 - 多列连接
- vhdl - 即使没有显示错误,VHDL 仿真也会挂起
- python - 如何从 QPlainTextEdit 正确获取 Unicode 文本输入?
- javascript - API 返回 JSON 与 Javascript