import requests
from bs4 import BeautifulSoup
"""
1. HTML 基本格式
<html>
| |
<head> <body>
| | |
<title> <p> <p>
| | |
<b> <a> <a>
2. 标签树的下行遍历
属性 说明
.contents: 子节点的列表,将<tag>所有儿子节点存入列表
.children: 子节点的迭代类型,与.contents类型,用于循环遍历儿子节点
.descendants: 子孙节点的迭代类型,包含所有子孙节点,用于循环遍历
3. 标签树的上行遍历
属性 说明
.parent 节点的父亲标签
.parents 节点先辈的迭代类型,用于循环遍历先辈节点
4. 标签树的平行遍历
前提:平行遍历发生在同一个父亲节点下的各个节点之间
属性 说明
.next_sibling 返回按照HTML文本顺序的下一个平行节点标签
.previous_sibling 返回按照HTML文本顺序的上一个平行节点标签
.next_siblings 迭代类型,返回按照HTML文本顺序的后续所有平行节点标签
.previous_siblings 迭代类型,返回按照HTML文本顺序的前续所有平行节点标签
"""
if __name__ == '__main__':
r = requests.get("https://python123.io/ws/demo.html")
demo = r.text
soup = BeautifulSoup(demo, 'html.parser')
print(soup.prettify())
# 上行遍历=-打印结果:[<title>This is a python demo page</title>]
print(soup.head.contents)
# 下行遍历-打印title标签的父亲节点结果:<head><title>This is a python demo page</title></head>
print(soup.title.parent)
# 平行遍历-打印a标签的下一个节点结果: and
print(soup.a.next_sibling)
# 平行遍历-打印a标签的上一个节点结果:Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses:
print(soup.a.previous_sibling)
5. 运行结果
C:\Users\珞落\AppData\Local\Programs\Python\Python39\python.exe D:/PythonProject/main.py
<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 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>
</body>
</html>
[<title>This is a python demo page</title>]
<head><title>This is a python demo page</title></head>
and
Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses:
Process finished with exit code 0