Python--BeautifulSoup库的介绍


当前第2页 返回上一页

其中,BeautifulSoup类型是标签树的根节点。

1

1 # 遍历儿子节点2 for child in soup.body.children:3     print(child.name)4 5 # 遍历子孙节点6 for child in soup.body.descendants:7     print(child.name)

标签树的上行遍历

1

1 # 遍历所有先辈节点时,包括soup本身,所以要if...else...判断2 for parent in soup.a.parents:3     if parent is None:4         print(parent)5     else:6         print(parent.name)

运行结果:

div

div

body

html

[document]

标签树的平行遍历

1

1 # 遍历后续节点2 for sibling in soup.a.next_sibling:3     print(sibling)4 5 # 遍历前续节点6 for sibling in soup.a.previous_sibling:7     print(sibling)

bs4库的prettify()方法

prettify()方法可以将代码格式搞的标准一些,用soup.prettify()表示。在PyCharm中,用print(soup.prettify())来输出。

操作环境:Mac,Python 3.6,PyCharm 2016.2

参考资料:中国大学MOOC课程《Python网络爬虫与信息提取》

以上就是Python--BeautifulSoup库的介绍的详细内容,更多文章请关注木庄网络博客!!

返回前面的内容

相关阅读 >>

Python中+=连用是什么意思

Python smtp发送邮件的详细介绍(附代码)

Python里//什么意思

Python字典中如何一键多值的写入?

Python初学者常见的七种错误及解决方法

关于Python 下划线使用场景

Python的基本数据类型有哪些?

什么是Python cgi编程?编程前需要做哪些准备?

Python 的二元算术运算详解

Python中如何搭建虚拟环境?Python搭建虚拟环境的步骤

更多相关阅读请进入《Python》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...