beautifulsoup:如何获取表头中元素的索引

Eri*_*ins 2 python beautifulsoup html-parsing

我正在尝试提取表头中的元素索引,以便我可以使用结果在表的主体中选择适当的列.列的数量不尽相同,但我需要的列在标题方面保持不变.

所以我想知道,例如,'third'是表格标题中的索引[2],因此<th>第一</ 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  
Run Code Online (Sandbox Code Playgroud)

得到:

ValueError:Tag.index:元素不在标记中

有什么想法吗?

ale*_*cxe 6

您可以找到所有标题并使用相应的文本获取标题的位置:

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)

header_row = soup.select('table > thead > tr.myClass')[0]

headers = header_row.find_all('th')
header = header_row.find('th', text='A')
print headers.index(header)  # prints 0
Run Code Online (Sandbox Code Playgroud)