New to scrape table with python, and I would like to scrape the table of crime rates: the packages I used:
from bs4 import BeautifulSoup
import requests
import pandas as pd
import numpy as np
here is my code: loading empty array
data = []
page = requests.get("http://www.city-data.com/city/Belmont-Massachusetts.html")
soup = BeautifulSoup(page.content, "html.parser")
identify table we want to scrape
table = soup.find_all("table",{"class":"table tabBlue tblsort tblsticky sortable"})
loop through table, grab each of the 13 columns shown
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()
I use Mac os, python 3 however, in the last I got an empty list. Could anyone give me some suggestions?
The error I got I am guessing that because I had problem scrape h4 information(the header of the table is in the h4 area..)
I did scraping like this.
# 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)
Happy scraping !
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.