【问题标题】:beautifulsoup: how to get indexes of elements in table headersbeautifulsoup:如何获取表头中元素的索引
【发布时间】: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


    【解决方案1】:

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

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-03
      • 1970-01-01
      • 2020-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多