【发布时间】: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