python bs4 find_all_BeautifulSoup find_all()未找到所有请求的元素

string属性要求标记只包含文本而不包含标记。如果您尝试为第一个p标记打印.string,那么它将返回None,因为其中有标记。在

或者,为了更好地解释它,documentation说:If a tag has only one child, and that child is a NavigableString, the child is made available as .string

If a tag contains more than one thing, then it’s not clear what .string should refer to, so .string is defined to be None

克服这个问题的方法是使用lambda函数。在html = """

This has a color of red. Because it likes the color red

This paragraph has a color of blue.

This paragraph does not have a color.

"""

soup = BeautifulSoup(html, 'html.parser')

first_p = soup.find('p')

print(first_p)

#

This has a color of red. Because it likes the color red

print(first_p.string)

# None

print(first_p.text)

# This has a color of red. Because it likes the color red

paras = soup.find_all(lambda tag: tag.name == 'p' and 'color' in tag.text.lower())

print(paras)

# [

This has a color of red. Because it likes the color red

,

This paragraph has a color of blue.

,

This paragraph does not have a color.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值