[英]How to scrape the table from website with python-scrape h4 information
使用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區域中。)
我確實是這樣刮的。
# 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)
刮刮樂!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.