首页 > 解决方案 > 使用 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 作为输出。关于我做错了什么有什么建议吗?

提前致谢!

标签: htmlparsingxpathweb-scrapingweb-crawler

解决方案


我会使用 bs4 4.7.1。您可以在其中搜索具有文本:contains的单元格,然后获取相邻的兄弟。您可以添加测试以进行错误处理。不如长 xpath 脆弱。td"Bedrooms"tdis 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

推荐阅读