gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 21:19:15 24 4
gpt4 key购买 nike

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

所以我想知道,例如,'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: element not in tag

有什么想法吗?

最佳答案

您可以找到所有标题并获取带有适当文本的标题的位置:

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

关于python - beautifulsoup:如何获取表头中元素的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24995821/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com