>>> from bs4 import BeautifulSoup #从bs4库中导入BeautifulSoup类
>>> r = requests.get("http://python123.io/ws/demo.html")
>>> r.text
'<html><head><title>This is a python demo page</title></head>\r\n<body>\r\n<p class="title"><b>The demo python introduces several python courses.</b></p>\r\n<p class="course">Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses:\r\n<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>\r\n</body></html>'
>>> demo = r.text #将请求的内容放入demo中
>>> soup = BeautifulSoup(demo,"html.parser") #定义变量soup
>>> soup.parent
>>> soup.a.parent #查找a标签的父亲标签<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>
>>> for parent in soup.a.parents:
if parent is None:
print(parent)
else:
print(parent.name)
#对soup的a标签所有的先辈标签进行打印p
body
html
[document]