首页 > 解决方案 > BeautifulSoup 将数据组织到数据框表中

问题描述

我一直在与 BeautifulSoup 合作,尝试组织一些我从网站 (html) 中提取的数据

  1. 消除不需要的信息
  2. 组织剩余数据以放入 pandas 数据框

这是我正在使用的代码:

import urllib.request
from bs4 import BeautifulSoup as bs
import re
import pandas as pd
import requests

headers = requests.utils.default_headers()
headers.update({
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36'
})

url = 'https://www.apartments.com/lehi-ut/1-bedrooms/'

page = requests.get(url,headers = headers)

soup = bs(page.text)

names = soup.body.findAll('tr')
function_names = re.findall('th class="\w+', str(names))
function_names = [item[10:] for item in function_names]

description = soup.body.findAll('td')
#description = re.findall('td class="\w+', str(description))

data = pd.DataFrame({'Title':function_names,'Info':description})

我得到的错误是数组编号不匹配,我知道这是真的,但是当我取消第二个描述行的标签时,它会从那里删除我想要的数字,即使那样表格也不是适当地组织自己。

我希望输出看起来像:

(headers)  title: location | studio | 1 BR | 2 BR | 3 BR
(new line) data :  Lehi, UT| $1,335 |$1,309|$1,454|$1,580    

这确实是我所需要的,但我无法让 BS 或 Pandas 正确地做到这一点。

任何帮助将不胜感激!

标签: pythonpandasdataframebeautifulsoup

解决方案


尝试以下方法。它首先提取表中的所有数据,然后对其进行转置(列与行交换):

import urllib.request
from bs4 import BeautifulSoup as bs
import re
import pandas as pd
import requests

headers = {
    'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36'
}

url = 'https://www.apartments.com/lehi-ut/1-bedrooms/'
page = requests.get(url, headers=headers)
soup = bs(page.text, 'lxml')
table = soup.find("table", class_="rentTrendGrid")
rows = []

for tr in table.find_all('tr'):
    rows.append([td.text for td in tr.find_all(['th', 'td'])])

#header_row = rows[0]
rows = list(zip(*rows[1:])) # tranpose the table
df = pd.DataFrame(rows[1:], columns=rows[0])
print(df)

为您提供以下类型的输出:

   Studio    1 BR    2 BR    3 BR
0       0     729   1,041   1,333
1  $1,335  $1,247  $1,464  $1,738

推荐阅读