【发布时间】:2017-08-31 19:09:09
【问题描述】:
所以我正在尝试使用 BeautifulSoup 4.0 从Michigan Department of Health and Human Services website 上的表中抓取数据,但我不知道如何正确格式化它。
我编写了下面的代码来从网站获取信息,但我不知道如何格式化它,以便在我打印它或将其另存为时它与网站上的表格具有相同的外观.txt/.csv 文件。我已经在这里和许多其他网站上寻找答案,但我不确定如何继续进行。我是一个非常初学者,所以任何帮助将不胜感激。
我的代码只打印了一个长列表,其中包含表格行或表格数据:
import urllib2
import bs4
from bs4 import BeautifulSoup
url = "https://www.mdch.state.mi.us/osr/natality/BirthsTrends.asp"
page = urllib2.urlopen(url)
soup = BeautifulSoup((page), "html.parser")
table = soup.find("table")
rows = table.find_all("tr")
for tr in rows:
tds = tr.find_all('td')
print tds
我正在查看的 HTML 也在下面:
<table border=0 cellpadding=3 cellspacing=0 width=640 align="center">
<thead style="display: table-header-group;">
<tr height=18 align="center">
<th height=35 align="left" colspan="2">County</th>
<th height="35" align="right">
2005
</th>
该部分将年份显示为标题并一直到 2015 年,然后州和县的数据进一步向下:
<tr height="40" >
<th class="LeftAligned" colspan="2">Michigan</th>
<td>
127,518
</td>
对于其他县,依此类推。 再次感谢任何帮助。
【问题讨论】:
-
你所要做的就是创建一个多维数组(行 -> 列),你就可以了。
-
请原谅我的无知,但就代码而言,我将如何做到这一点?
标签: python html beautifulsoup html-table