【问题标题】:Extracting selected columns from a table using BeautifulSoup使用 BeautifulSoup 从表中提取选定的列
【发布时间】:2012-10-15 23:46:36
【问题描述】:

我正在尝试使用 BeautifulSoup 提取 this data table 的第一列和第三列。从 HTML 来看,第一列有一个 <th> 标记。感兴趣的另一列具有<td> 标记。无论如何,我所能得到的只是带有标签的列的列表。但是,我只想要文字。

table 已经是一个列表,所以我不能使用findAll(text=True)。我不确定如何以另一种形式获取第一列的列表。

from BeautifulSoup import BeautifulSoup
from sys import argv
import re

filename = argv[1] #get HTML file as a string
html_doc = ''.join(open(filename,'r').readlines())
soup = BeautifulSoup(html_doc)
table = soup.findAll('table')[0].tbody.th.findAll('th') #The relevant table is the first one

print table

【问题讨论】:

  • 我不相信您将能够获得整个列,因为 HTML 表示是基于行的(尽管可能是错误的)。我想您可以通过遍历行并拉出相应的列,将其添加到您选择的数据结构中来近似某些东西。
  • 我开始尝试了,但仍然无法提取文本。我将更新我的答案以包括该部分。也许这是一种更简单的方法。

标签: python html-parsing beautifulsoup


【解决方案1】:

你可以试试这个代码:

import urllib2
from BeautifulSoup import BeautifulSoup

url = "http://www.samhsa.gov/data/NSDUH/2k10State/NSDUHsae2010/NSDUHsaeAppC2010.htm"
soup = BeautifulSoup(urllib2.urlopen(url).read())

for row in soup.findAll('table')[0].tbody.findAll('tr'):
    first_column = row.findAll('th')[0].contents
    third_column = row.findAll('td')[2].contents
    print first_column, third_column

如您所见,代码只是连接到 url 并获取 html,BeautifulSoup 找到第一个表,然后所有 'tr' 并选择第一列,即 'th',然后选择第三列,这是一个'td'。

【讨论】:

    【解决方案2】:

    除了@jonhkr 的回答,我想我会发布一个我想出的替代解决方案。

     #!/usr/bin/python
    
     from BeautifulSoup import BeautifulSoup
     from sys import argv
    
     filename = argv[1]
     #get HTML file as a string
     html_doc = ''.join(open(filename,'r').readlines())
     soup = BeautifulSoup(html_doc)
     table = soup.findAll('table')[0].tbody
    
     data = map(lambda x: (x.findAll(text=True)[1],x.findAll(text=True)[5]),table.findAll('tr'))
     print data
    

    与 jonhkr 的答案不同,它会拨入网页,我假设您将其保存在计算机上并将其作为命令行参数传递。例如:

    python file.py table.html 
    

    【讨论】:

      【解决方案3】:

      你也可以试试这个代码

      import requests
      from bs4 import BeautifulSoup
      page =requests.get("http://www.samhsa.gov/data/NSDUH/2k10State/NSDUHsae2010/NSDUHsaeAppC2010.htm")
      soup = BeautifulSoup(page.content, 'html.parser')
      for row in soup.findAll('table')[0].tbody.findAll('tr'):
          first_column = row.findAll('th')[0].contents
          third_column = row.findAll('td')[2].contents
          print (first_column, third_column)
      

      【讨论】:

        猜你喜欢
        • 2019-11-15
        • 1970-01-01
        • 1970-01-01
        • 2017-11-11
        • 1970-01-01
        • 2016-02-16
        • 1970-01-01
        • 1970-01-01
        • 2016-06-15
        相关资源
        最近更新 更多