首页 > 解决方案 > 具有 tr 类数据键的 Webscraping 表

问题描述

我是 python 的新手,所以对我来说很赤裸裸。我正在尝试从房地产数据网站上的数据集表中抓取一个表。我之前在我所在地区(阿拉伯联合酋长国)的一个房地产列表网站上运行了一个类似的想法https://propertyfinder.ae我会在其中运行类似于此的脚本。

from bs4 import BeautifulSoup
from requests import get
import pandas as pd
import itertools
import matplotlib.pyplot as plt
import seaborn as sns
sns.set()

headers = ({'User-Agent':
            'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36'})

# Search Page with parameters included
pf = 'https://www.propertyfinder.ae/en/search?c=1&ob=mr&page=1'

response =  get(pf, headers=headers)
html_soup = BeautifulSoup(response.text, 'html.parser')

listings = html_soup.find_all('div', class_="card-list__item")
first = listings[0]

#Location Variable
location = first.find_all('p', class_='card__location')[0].text

#Size (sqft)
size = first.find_all('p', class_='card__property-amenity card__property-amenity--area')[0].text

对于其他变量,依此类推。

然而,在这个新的数据网站上,他们的 html 布局引入了一个我不知道如何使用 find_all() 函数的类类型。

<table class="_1_lam64P">
        <thead>...</thead>
        <body>
                <tr class data-key="table-row_0">...</tr>
                <tr class data-key="table-row_1">...</tr>
                <tr class data-key="table-row_2">...</tr>

我尝试执行以下操作(即使我知道它不会帮助我进行索引),但它告诉我关键字不能是表达式。

listings = html_soup.find_all('tr', class_data-key_="table-row_0")

考虑到这一点,我希望能够通过索引'table-row_X'和'X'前进到每个数字来循环每个表格行和后续页面。同样,我需要以 html5 格式获取变量

<tr class data-key="table-row_0">
        <td colspan="1" data-key="data-table-cell_price">..</td>
        <td colspan="1" data-key="data-table-cell_plot_area">..</td>
</tr>

我将如何访问 td 属性?

提前致谢。

PS我用这个作为指南

https://towardsdatascience.com/looking-for-a-house-build-a-web-scraper-to-help-you-5ab25badc83e

标签: pythonweb-scrapingbeautifulsoup

解决方案


要从该表中获取所有值,您可以忽略每一行的类,只读取所有的<tr><td>元素。标题也可以通过<th>元素获得:

from bs4 import BeautifulSoup
import pandas as pd

with open('Record Data - Data Finder.html') as f_html:
    html = f_html.read()

soup = BeautifulSoup(html, 'html.parser')
header = [th.text for th in soup.table.find_all('th')]
data = []

for tr in soup.table.find_all('tr'):
    data.append([td.text for td in tr.find_all('td')])
    
df = pd.DataFrame(data, columns=header)
print(df)

推荐阅读