python - 使用 Python 2.7 使用 Beautiful Soup 提取并打印表头和数据

标签 python html beautifulsoup html-table

所以我试图从 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/

相关文章:

python - 后面加*args可以使用默认参数吗?

python - 使用summary_out时将回归结果导出为csv文件

c# - MVC。由于某种原因,动态 css 样式为空

javascript - 您可以将 html 文件渲染到容器中吗?

python - 使用 BeautifulSoup 从 html 中仅提取除脚本标签内容之外的文本

python - 使用 BeautifulSoup 与基本表的选项 - 无类 ID,

python - 无法使用 xpath 获取 Selenium RC 的属性值

python - 你如何打印字母之间有一点时间的单词? (Python)

javascript - html中的表单点击提交按钮时无法提交数据?

python - 查找 HTML 中的所有标签和属性