python - 如何使用 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 区域中..)
解决方案
我是这样刮的。
# 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)
快乐刮!
推荐阅读
- csv - 使用 HTML 报告 Dashboard 分析 jmeter 负载测试的结果
- swift - 如何使用导航栏移动另一个故事板?
- swift - RxSwift 链接请求
- nginx - 如何将子域指向同一服务器上的另一个“文件夹”?
- angular - 如何在角度 MatTable 中排序后获取更新的 Viewchildren 参考
- excel-formula - 返回过滤数据的列总和,没有过滤器
- liferay - Liferay 错误的自动增量
- sql-server - 如何创建 SQL 触发器以在更新另一个表时更新一个表上的日期字段
- php - PhpStorm - 将 PHP 传递给 Vue 组件时“预期表达式”和“切换语言以反应”
- android - 调用不同调度android组件的合适位置是什么