标签:orm XML from bsp pytho amp size style HERE
1.什么是BeautifulSoup4
BS4是一个解析库,可以通过某种(解析器)来帮我们提取想要的
2.为什么要用BS4
它可以用简洁的语言帮我们快速提取想要的数据
3.解析器的分类
(1)html.parser
(2)lxml
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 sisters; 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
#python自带的解析库
soup=BeautifulSoup(html_doc,‘html.parser‘)
#调用bs4得到一个soup对象
soup=BeautifulSoup(html_doc,‘lxml‘)
#bs4对象
print(soup)
#bs4类型
print(type(soup))
#美化功能
html=soup.prettify() # print(html)
遍历文档树(前三较为重要)
# 1、直接使用
print(soup.html) print(type(soup.html)) print(soup.a)
# 2、获取标签的属性
print(soup.a.attrs[‘href‘])
# 3、获取标签的内容
print(soup.p.text)
# 4、获取标签的名称
print(soup.a.name)
#5、嵌套选择
print(soup.html.body.p)
# 6、子节点、子孙节点
print(soup.p.children)#返回迭代器对象 print(list(soup.p.children))
# 7、父节点、祖先节点
print(soup.p.parents) print(list(soup.p.parents))
# 8、兄弟节点
print(soup.a) # 获取下一个兄弟节点 print(soup.a.next_sibling) # 获取下一个的所有兄弟节点,返回的是一个生成器 print(soup.a.next_siblings) print(list(soup.a.next_siblings)) # 获取上一个兄弟节点 print(soup.a.previous_sibling) # 获取上一个的所有兄弟节点,返回的是一个生成器 print(list(soup.a.previous_siblings))
标签:orm XML from bsp pytho amp size style HERE
原文地址:https://www.cnblogs.com/changgeyimeng/p/11128475.html