python-如何查找仅具有某些属性的标签-BeautifulSoup
如何使用BeautifulSoup搜索仅包含我要搜索的属性的标签?
例如,我要查找所有
标签。如下代码:
获取我想要的所有数据,还获取具有属性
的任何标签我也尝试过:
这什么也不返回(可能是由于正则表达式不正确)我想知道在BeautifulSoup中是否可以说“找到
标签,其唯一属性是”更新例如,如果HTML文档包含以下
标签:.................我只希望返回第
个标记()Snaxib asked 2019-10-05T18:54:04Z
6个解决方案
76 votes
如BeautifulSoup文档中所述
您可以使用:
soup = BeautifulSoup(html)
results = soup.findAll("td", {"valign" : "top"})
编辑:
要返回仅具有valign =“ top”属性的标签,您可以检查标签attrs属性的长度:
from BeautifulSoup import BeautifulSoup
html = '
.....\.......\.....'soup = BeautifulSoup(html)
results = soup.findAll("td", {"valign" : "top"})
for result in results :
if len(result.attrs) == 1 :
print result
返回:
.....Loïc G. answered 2019-10-05T18:54:38Z
33 votes
您可以按照文档中的说明在findAll中使用lambda函数。 因此,在您的情况下仅使用valign = "top"来搜索td标记,请使用以下代码:
td_tag_list = soup.findAll(
lambda tag:tag.name == "td" and
len(tag.attrs) == 1 and
tag["valign"] == "top")
Yogesh answered 2019-10-05T18:55:03Z
15 votes
如果您只想搜索具有任何值的属性名称
from bs4 import BeautifulSoup
import re
soup= BeautifulSoup(html.text,'lxml')
results = soup.findAll("td", {"valign" : re.compile(r".*")})
根据Steve Lorimer的说法,最好通过True而不是regex
results = soup.findAll("td", {"valign" : True})
Amr answered 2019-10-05T18:55:35Z
8 votes
最简单的方法是使用新的CSS样式select方法:
soup = BeautifulSoup(html)
results = soup.select('td[valign="top"]')
Chris Redford answered 2019-10-05T18:56:01Z
3 votes
只需将其作为findAll的参数传递即可:
>>> from BeautifulSoup import BeautifulSoup
>>> soup = BeautifulSoup("""
...
...
My Title!...
...
First!...
Second!...
... """)
>>>
>>> soup.findAll('td')
[
First!, Second!]>>>
>>> soup.findAll('td', valign='top')
[
Second!]juliomalegria answered 2019-10-05T18:56:27Z
0 votes
添加Chris Redford和Amr的答案,您还可以使用select命令搜索具有任何值的属性名称:
from bs4 import BeautifulSoup as Soup
html = '
.....\.......\.....'soup = Soup(html, 'lxml')
results = soup.select('td[valign]')
GrazingScientist answered 2019-10-05T18:56:53Z