【发布时间】:2014-07-28 12:58:04
【问题描述】:
我正在尝试提取表格标题中元素的索引,以便稍后在表格正文中使用结果来选择适当的列。列的数量各不相同,但我需要的列的标题保持不变。
所以我想知道,例如,'third' 是表标题中的索引 [2],因此 ‹th>first‹/th>‹th>second‹/th>‹th>third ‹/th>‹th>第四‹/th>‹th>第五‹/th> 然后我可以通过选择‹td>的索引号有选择地选择以下行中的相关‹td>。
这是我的尝试:
#TRIAL TO GET INDEXES FROM TABLE HEADERS
from bs4 import BeautifulSoup
html = '<table><thead><tr class="myClass"><th>A</th>'
'<th>B</th><th>C</th><th>D</th></tr></thead></table>'
soup = BeautifulSoup(html)
table = soup.find('table')
for hRow in table.find_all('th'):
hRow = hRow.index('A')
print hRow
给:
ValueError: Tag.index: 元素不在标签中
有什么想法吗?
【问题讨论】:
标签: python beautifulsoup html-parsing