纪年科技aming
网络安全 ,深度学习,嵌入式,机器强化,生物智能,生命科学。
解析库 – lxml
安装lxml库 (支持HTML和XML解析,支持XPath解析方式)
pip install lxml
Xpath
在 XPath 中,有七种类型的节点:
元素、属性、文本、命名空间、处理指令、注释以及文档(根)节点。
XML 文档是被作为节点树来对待的。
树的根被称为文档节点或者根节点。
节点关系
父(Parent)、子(Children) 每个元素以及属性都有一个父。
book 元素是 title、author、year 以及 price 元素的父
title、author、year 以及 price 元素都是 book 元素的子
title、author、year 以及 price 元素都是同胞:
title 元素的先辈是 book 元素和 bookstore 元素
bookstore 的后代是 book、title、author、year 以及 price 元素
节点选取
XPath 使用路径表达式在 XML 文档中选取节点。
节点是通过沿着路径或者 step 来选取的。
获取页面元素xpath路径的快捷方式
BeautifulSoup4解析器
BeautifulSoup4是一个HTML/XML的解析器,
主要的功能是解析和提取HTML/XML的数据。和lxml库一样
lxml只会局部遍历,
而BeautifulSoup4是基于HTML DOM的,会加载整个文档,解析整个DOM树,
因此内存开销比较大,性能比较低。
BeautifulSoup4用来解析HTML比较简单,API使用非常人性化,
支持CSS选择器,是Python标准库中的HTML解析器,
也支持lxml解析器。
————————————————
BeautifulSoup4的安装
pip install beautifulsoup4
# 获取title标签
print(soup.title)
# <title>The Dormouse's story</title>
# 获取title标签名称
print(soup.title.name)
# title
# 获取title标签的内容
print(soup.title.string)
# The Dormouse's story
# 获取title的父标签
print(soup.title.parent)
# <head><title>The Dormouse's story</title></head>
# 获取title的父标签名称
print(soup.title.parent.name)
# head
# 获取p标签
print(soup.p)
# <p class="title"><b>The Dormouse's story</b></p>
# 获取p标签class属性
print(soup.p['class'])
# ['title'] #返回的是list
# 获取所有的a标签
print(soup.find_all('a'))
# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
# 获取id='link3'的标签
print(soup.find(id="link3"))
# <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>
# 获取所有的a标签的链接
for link in soup.find_all('a'):
print(link.get('href'))
# http://example.com/elsie
# http://example.com/lacie
# http://example.com/tillie
# 获取文档中所有文字内容
print(soup.get_text())
# The Dormouse's story
#
# The Dormouse's story
# Once upon a time there were three little sisters; and their names were
# Elsie,
# Lacie and
# Tillie;
# and they lived at the bottom of a well.
# ...