DAY03:BS4

html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="sister"><b>$37</b></p>

<p class="story" id="p">Once upon a time there were three little sistes; and their names were
<a href="http://example.com/elsie" class="sister" >Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>

<p class="story">...</p>
"""
from bs4 import BeautifulSoup

#遍历文档树
soup = BeautifulSoup(html_doc,'lxml')
#print(soup)
#print(type(soup))
#遍历文档树
#1.直接使用 ********
print(soup.html)
print(type(soup.html))
print(soup.a)
print(soup.p)
#获取标签的名称
print(soup.a.name)
#获取标签的属性
print(soup.a.attrs)
print(soup.a.attrs['href'])
#获取标签的内容
print(soup.p.text)
#嵌套选择
print(soup.html.body.p)
#子节点,子孙节点
print(soup.p.children)
print(list(soup.p.children))

#父节点,祖先节点
print(soup.b.parent)
print(soup.b.parents)
print(list(soup.b.parents))

#兄弟节点(sibling:兄弟姐妹)
print(soup.a
#获取下一个兄弟节点
print(soup.a.next_sibling)
#获取下一个的所有兄弟节点,返回的是一个生成器
print(soup.a.previous_sibling)
#获取上一个的所有兄弟节点,返回的是一个生成器
print(list(soup.a.previous_siblings ))

#第一个参数是解析文本
#第二个参数是解析器
#soup = BeautifulSoup(html_doc,'lxml')

#具备自动补全html标签功能
#print(soup)

#美化html便签
#html_doc = soup.prettify()
#print(html_doc)
上一篇:BeautifulSoup库的简单实用


下一篇:Python : 爬虫--BeautifulSoup