之前通过h1标题查找表

时间:2017-05-25 10:49:56

标签: python html beautifulsoup html-parsing

我想在使用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>
&#13;
&#13;
&#13;

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

2 个答案:

答案 0 :(得分:2)

我认为您应该在BeautifulSoup中使用h1+table,因为表格位于h1

之下

答案 1 :(得分:0)

由于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>]