【发布时间】:2019-01-26 21:24:30
【问题描述】:
我正在使用 BeautifulSoup 来解析 HTML 文件。我有一个类似这样的 HTML 文件:
<h3>Unimportant heading</h3>
<table class="foo">
<tr>
<td>Key A</td>
</tr>
<tr>
<td>A value I don't want</td>
</tr>
</table>
<h3>Unimportant heading</h3>
<table class="foo">
<tr>
<td>Key B</td>
</tr>
<tr>
<td>A value I don't want</td>
</tr>
</table>
<h3>THE GOOD STUFF</h3>
<table class="foo">
<tr>
<td>Key C</td>
</tr>
<tr>
<td>I WANT THIS STRING</td>
</tr>
</table>
<h3>Unimportant heading</h3>
<table class="foo">
<tr>
<td>Key A</td>
</tr>
<tr>
<td>A value I don't want</td>
</tr>
</table>
我想提取字符串“I WANT THIS STRING”。完美的解决方案是获得在名为“THE GOOD STUFF”的 h3 标题之后的第一个表格。我不知道如何使用 BeautifulSoup 执行此操作 - 我只知道如何提取具有特定类的表,或 嵌套在某个特定标签内的表,但不知道 following一个特定的标签。
我认为后备解决方案可以使用字符串“Key C”,假设它是唯一的(几乎可以肯定是)并且只出现在那个表中,但使用特定的 h3 标题我会感觉更好。
【问题讨论】:
标签: python python-3.x beautifulsoup html-parsing