如何使用BeautifulSoup为HTML嵌套标签定义findAll

2 投票
2 回答
16449 浏览
提问于 2025-04-16 11:24

给定

<a href="www.example.com/"></a>

<table class="theclass">
<tr><td>
<a href="www.example.com/two">two</a>
</td></tr>
<tr><td>
<a href ="www.example.com/three">three</a>
<span>blabla<span>
</td></td>
</table>

我该如何只抓取在类名为 "the class" 的表格里面的内容呢?我试过使用

soup = util.mysoupopen(theexample) 
infoText = soup.findAll("table", {"class": "the class"})

但我不知道怎么进一步定义查找的语句。我还尝试过把 findAll() 的结果变成一个数组,然后寻找针出现的模式,但我找不到一个稳定的模式。谢谢

2 个回答

2

infoText 是一个列表。你应该对它进行遍历。

>>>for info in infoText:
>>>    print info.tr.td.a
<a href="www.example.com/two">two</a>

然后你就可以访问 <table> 元素。如果你在文档中只期待有一个类名为 "theclass" 的表格元素,使用 soup.find("table", {"class": "the class"}) 就可以直接找到这个表格。

4

如果我理解你的问题没错的话,这段Python代码应该是可以工作的。它的意思是:循环查找所有类名为"theclass"的表格,然后在这些表格里面找到链接。

>>> foo = """<a href="www.example.com/"></a>
... <table class="theclass">
... <tr><td>
... <a href="www.example.com/two">two</a>
... </td></tr>
... <tr><td>
... <a href ="www.example.com/three">three</a>
... <span>blabla<span>
... </td></td>
... </table>
... """
>>> import BeautifulSoup as bs
>>> soup = bs.BeautifulSoup(foo)
>>> for table in soup.findAll('table', {'class':'theclass'} ):
...     links=table.findAll('a')
... 
>>> print links
[<a href="www.example.com/two">two</a>, <a href="www.example.com/three">three</a>]

撰写回答