python tag对象下有多个标签、属性_python-如何查找仅具有某些属性的标签-BeautifulSoup...

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值