首页 > 解决方案 > 如何使用 python-scrape h4 信息从网站上抓取表格

问题描述

新手用python刮表,我想刮犯罪率表:我使用的包:

from bs4 import BeautifulSoup
import requests
import pandas as pd
import numpy as np

这是我的代码:加载空数组

data = []
page = requests.get("http://www.city-data.com/city/Belmont-Massachusetts.html")
soup = BeautifulSoup(page.content, "html.parser")

识别我们要抓取的表

table = soup.find_all("table",{"class":"table tabBlue tblsort tblsticky sortable"})

循环遍历表,抓取显示的 13 列中的每一列

for row in table.find_all('tr'):
    cols = row.find_all('h4').get_text()
    if len(cols) == 13:
        data.append((cols[0].text.strip(), cols[1].text.strip(), cols[2].text.strip(), cols[3].text.strip(),cols[4].text.strip(),cols[5].text.strip(),cols[6].text.strip(),cols[7].text.strip(),cols[8].text.strip(),cols[9].text.strip(),cols[10].text.strip(),cols[11].text.strip(),cols[12].text.strip(),cols[13].text.strip()))
except: pass 


data = np.asarray(data)
len(data)
df = pd.DataFrame(data)
df.head()

我使用 Mac os,python 3 然而,最后我得到了一个空列表。谁能给我一些建议?

我得到的错误我猜是因为我在抓取 h4 信息时遇到问题(表的标题在 h4 区域中..)

标签: pythonweb-scrapingbeautifulsoup

解决方案


我是这样刮的。

# yes, you identified the right table
right_table=soup.find('table', {"class":'table tabBlue tblsort tblsticky sortable'})

rows = right_table.findAll("tr")

# header attributes of the table
header = [th.text.rstrip() for th in rows[0].find_all('th')]

# data
lst_data = []
for row in rows[1:]:
            data = [d.text.rstrip() for d in row.find_all('td')]
            lst_data.append(data)

# your expected result
df = pd.DataFrame(lst_data, columns=header)
print(df)

快乐刮!


推荐阅读