>>> 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 class="py1" id="link1">Basic Python</a> and <a 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 class="py1" id="link1">Basic Python</a>
and
<a 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)