【问题标题】:Find a table by the h1 header before找一个表之前的h1表头
【发布时间】:2025-11-23 08:00:02
【问题描述】:

我想在使用 BeautifulSoup 之前使用 h1 在 HTML 中查找表格

<a name="playerlist"></a>
<div class="navbuttons">
<a href="#toc" class="linkbutton">up</a><a class="linkbutton" href="#players">next</a>
</div>
<h1>Participants</h1>
<table class="main">
<thead>
<tr>
<th>Name </th><th>Major</th><th>Class of</th><th>Ranking</th></tr>
</thead>
<tbody>
<tr>
<td>Mike Finge</td><td>Applied Maths</td><td>2015</td><td>155</td>
</tr>
</tbody>
</table>

在上面的示例中,我想在 h1 下找到表? 我怎么能用 BeautifulSoup 做到这一点? 提前致谢

【问题讨论】:

  • 用于表格边距-顶部:-30px;或任何其他合适的 -ve 值
  • 只使用h1 + table选择器

标签: python html beautifulsoup html-parsing


【解决方案1】:

我认为你应该在 BeautifulSoup 中使用h1+table,因为表格就在 h1 下方

【讨论】:

    【解决方案2】:

    由于table 元素是h1 的兄弟元素,您可以这样做,即,您可以使用select 方法可用的~ 运算符。

    >>> HTML = '''\
    ... <a name="playerlist"></a>
    ... <div class="navbuttons">
    ... <a href="#toc" class="linkbutton">up</a><a class="linkbutton" href="#players">next</a>
    ... </div>
    ... <h1>Participants</h1>
    ... <table class="main">
    ... <thead>
    ... <tr>
    ... <th>Name </th><th>Major</th><th>Class of</th><th>Ranking</th></tr>
    ... </thead>
    ... <tbody>
    ... <tr>
    ... <td>Mike Finge</td><td>Applied Maths</td><td>2015</td><td>155</td>
    ... </tr>
    ... </tbody>
    ... </table>
    ... '''
    >>> from bs4 import BeautifulSoup
    >>> soup = BeautifulSoup(HTML, 'lxml')
    >>> soup.select('h1 ~ table')
    [<table class="main">
    <thead>
    <tr>
    <th>Name </th><th>Major</th><th>Class of</th><th>Ranking</th></tr>
    </thead>
    <tbody>
    <tr>
    <td>Mike Finge</td><td>Applied Maths</td><td>2015</td><td>155</td>
    </tr>
    </tbody>
    </table>]
    

    【讨论】:

      最近更新 更多