>>> import requests
>>> r = requests.get("http://python123.io/ws/demo.html")
>>> demo = r.text
>>> 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>'
HTML基本格式
<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>
标签树的下行遍历
属性
说明
.contents
子节点的列表,将<tag>所有儿子节点存入列表
.children
子节点的迭代类型,与.contents类似,用于循环遍历儿子节点
.descendants
子孙节点的迭代类型,包含所有子孙节点,用于循环遍历
for child in soup.body.children:
print(child)
标签树的上行遍历
属性
说明
.parent
节点的父亲标签
.parents
节点先辈标签的迭代类型,用于循环遍历先辈节点
>>> soup = BeautifulSoup(demo, "html.parser")
>>> for parent in soup.a.parents:
if parent is None:
print(parent)
else:
print(parent.name)
标签树的平行遍历
属性
说明
.next_sibling
返回按照HTML文本顺序的下一个平行节点标签
.previous_sibling
返回按照HTML文本顺序的上一个平行节点标签
.next_siblings
迭代类型,返回按照HTML文本顺序的后续所有平行节点标签
.previous_siblings
迭代类型,返回按照HTML文本顺序的前续所有平行节点标签
for sibling in soup.a.next_siblings:
print(sibling)
for sibling in soup.a.previous_siblings:
print(sibling)