如何找到只有特定属性的标签 - BeautifulSoup

132 投票
9 回答
210553 浏览
提问于 2025-04-17 10:39

我想知道如何使用BeautifulSoup来搜索只包含我想要的属性的标签。

比如,我想找到所有的 <td valign="top"> 标签。

下面这段代码:

raw_card_data = soup.fetch('td', {'valign':re.compile('top')})

能获取我想要的所有数据,但同时也会抓取任何带有 valign:top 属性的 <td> 标签。

我还尝试过:

raw_card_data = soup.findAll(re.compile('<td valign="top">'))

但这没有返回任何结果(可能是因为正则表达式写得不好)。

我在想,是否有办法在BeautifulSoup中指定“找到那些唯一属性是 valign:top<td> 标签”呢?

更新

举个例子,如果一个HTML文档包含以下的 <td> 标签:

<td valign="top">.....</td><br />
<td width="580" valign="top">.......</td><br />
<td>.....</td><br />

我只想要第一个 <td> 标签(<td width="580" valign="top">)的结果。

9 个回答

61

如果你只想根据属性名称来搜索,不管它的值是什么

from bs4 import BeautifulSoup
import re

soup= BeautifulSoup(html.text,'lxml')
results = soup.findAll("td", {"valign" : re.compile(r".*")})

根据Steve Lorimer的建议,传递True会比使用正则表达式更好

results = soup.findAll("td", {"valign" : True})
66

你可以在 findAll 里使用 lambda 函数,具体的用法可以参考这份文档。所以在你的情况下,如果想要查找只包含 valign = "top"td 标签,可以使用以下代码:

td_tag_list = soup.findAll(
                lambda tag:tag.name == "td" and
                len(tag.attrs) == 1 and
                tag["valign"] == "top")
149

BeautifulSoup的文档中有解释。

你可以使用这个:

soup = BeautifulSoup(html)
results = soup.findAll("td", {"valign" : "top"})

编辑:

如果你想找出只有valign="top"这个属性的标签,可以检查标签的attrs属性的长度:

from BeautifulSoup import BeautifulSoup

html = '<td valign="top">.....</td>\
        <td width="580" valign="top">.......</td>\
        <td>.....</td>'

soup = BeautifulSoup(html)
results = soup.findAll("td", {"valign" : "top"})

for result in results :
    if len(result.attrs) == 1 :
        print result

这样会返回:

<td valign="top">.....</td>

撰写回答