当前第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怎样实现百度语音识别api的步奏详解
Python与c不同之处
Python如何生成随机数字
Python的for循环怎么理解
Python file readlines() 使用方法
Python的字符串与下标定义与使用方法(内有示例与解析)
%s在Python中是什么意思
Python怎么安装jieba库
初学者编写Python用什么软件
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » Python--BeautifulSoup库的介绍