Reputation: 43
I want to find the table in a HTML using the h1 just before using BeautifulSoup
<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>
In the example above I would like to find the table just under h1 ? How can I do this with BeautifulSoup? Thanks in advance
Upvotes: 0
Views: 372
Reputation: 21663
Since the table
element is the sibling of the h1
you can do this, ie, you can use the ~
operator available for the select
method.
>>> 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>]
Upvotes: 0
Reputation: 66
I think you should use h1+table
in BeautifulSoup as table is just below h1
Upvotes: 2