所以我试图从 Michigan Department of Health and Human Services website 上的表中抓取数据使用 BeautifulSoup 4.0,我不知道如何正确格式化它。
我编写了下面的代码来从网站获取信息,但我不知道如何格式化它,以便在打印或另存为时它与网站上的表格具有相同的外观.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>
其余县以此类推。 再次强调,我们非常感谢任何帮助。
最佳答案
您需要将表格存储在列表中
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")
table_contents = [] # store your table here
for tr in rows:
if rows.index(tr) == 0 :
row_cells = [ th.getText().strip() for th in tr.find_all('th') if th.getText().strip() != '' ]
else :
row_cells = ([ tr.find('th').getText() ] if tr.find('th') else [] ) + [ td.getText().strip() for td in tr.find_all('td') if td.getText().strip() != '' ]
if len(row_cells) > 1 :
table_contents += [ row_cells ]
现在table_contents
与页面上的表格具有相同的结构和数据。
关于python - 使用 Python 2.7 使用 Beautiful Soup 提取并打印表头和数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43243557/