如何使用python-scrape h4信息从网站上抓取表格

时间:2019-08-21 22:03:01

标签: python web-scraping beautifulsoup

使用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区域中。)

1 个答案:

答案 0 :(得分:0)

我确实这样刮过。

# 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)

刮刮乐!