关于bs4的find_all函数访问多层标签的事项

关于bs4的find_all函数访问多层标签的事项

一、实验如下

>>> from bs4 import BeautifulSoup
>>> import requests
>>> html = requests.get("http://python123.io/ws/demo.html")
>>> demo = html.text
>>> soup = BeautifulSoup(demo, "html.parser")
>>> aaa=soup.find('p',attrs={'class':'course'})
>>> bbb=aaa.find_all(attrs={'class':'py2'})
>>> ccc=aaa.find_all(attrs={'class':'py2'})[0]
>>>> print(demo)
<html><head><title>This is a python demo page</title></head>
<body>
<p class="title"><b>The demo python introduces several python courses.</b></p>
<p class="course">Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses:
<a href="http://www.icourse163.org/course/BIT-268001" class="py1" id="link1">Basic Python</a> and <a href="http://www.icourse163.org/course/BIT-1001870001" class="py2" id="link2">Advanced Python</a>.</p>
</body></html>
>>> print(aaa)
<p class="course">Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses:
<a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a> and <a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">Advanced Python</a>.</p>
>>> type(aaa)
<class 'bs4.element.Tag'>
>>> print(bbb)
[<a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">Advanced Python</a>]
>>> type(bbb)
<class 'bs4.element.ResultSet'>
>>> print(ccc)
<a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">Advanced Python</a>
>>> type(ccc)
<class 'bs4.element.Tag'>

soup这个之前已经随便找了网页设置好了,第一行命令打印出demo的全部内容,其类型为<class ‘str’>。首先我们对P标签进行查找,通过设置的属性为条件。查找结果如上图所示,并赋值给变量aaa,通过查看类型可知道是<class ‘bs4.element.Tag’>。然后对aaa使用find_all函数进行查找,设置了属性为查找条件。这里可能大家觉得很奇怪。按理说aaa应该是列表类型啊,怎么会是tag。并且还有课用于下一次的find_all函数。但是事实就是这样。我们查找出了a标签,并赋值给变量bbb。通过查看类型可知是列表类型。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值