xpath基本知识html
XPath语法:使用路径表达式来选取XML或HTML文档中的节点或节点集node
路径表达式python
nodename:表示选取此节点的全部子节点正则表达式
/ : 表示从根节点选取ide
// :选择任意位置的某个节点。函数
. :选取当前节点测试
.. :选取当前节点的父节点spa
@ :选取属性ssr
谓语实例code
实现效果 路劲表达式
选取属于classroom子元素的第一个student元素 /classroom/student[1]
选取属于classroom子元素的最后一个student元素 /classroom/student[last()]
选取属于classroom子元素的倒数第二个stduent元素 /classroom/stduent[last()-1]
选取最前面的两个属于classroom元素的子元素的student元素 /classroom/stduent[position()<3]
选取全部拥有名为lang的属性的name元素 //name[@lang]
选取全部name元素,且这些元素拥有值为eng的lang属性 //name[@lang='en']
选取classroom元素的全部student元素,且其中的age元素的值须大于20 .classroom.stduent[age>20]
选取classroom元素中的student元素的全部name元素,且其中的age元素的值须大于20 /classroom/stduent[age>20]/name
通配符“*”与“|”操做
实现效果 路径表达式
选取classroom元素的全部子元素 /classroom/*
选取文档中的全部元素 //*
选取全部带有属性的name元素 //name[@*]
选取stduent元素的全部name和age元素 //stduent/name | //stduent/age
选取属于classroom元素的student元素的全部name元素,以及文档中全部的age元素 /classroom/stduent/name | //age
XPath轴 步的语法为 轴名称:节点测试[谓语]
轴名称 含义
child 选取当前节点的全部子节点
parent 选取当前节点的父节点
ancestor 选取当前节点的全部先辈(父、祖父等)
ancestor-or-self 选取当前节点的全部先辈以及当前节点自己
descendant 选取当前节点的全部后代节点
descendant-or-self 选取当前节点的全部后代节点以及当前节点自己
preceding 选取文档中当前节点的开始标记以前的全部节点
following 选取文档中当前节点的结束标记以后的全部节点
preceding-sibling 选取当前节点以前的全部同级节点
following-sibling 选取当前节点以后的所用同级节点
self 选取当前节点
attribute 选取当前节点的全部属性
namespace 选取当前节点的全部命名空间
XPath轴示例分析
实现效果 路径表达式
选取当前classroom节点中子元素的teacher节点 /classroom/child::teacher
选取全部id节点的父节点 //id/parent::*
选取全部以classid为子节点的祖先节点 //classid/ancestor::*
选取classroom节点下的全部后代节点 /classroom/descendant::*
选取全部以student为父节点的id元素 //student/descendant::id
选取全部classid元素的祖先节点及自己 //classid/ancestor-or-self::*
选择/classroom/student自己及其全部后代元素 /classroom/student/descendant-or-self::*
选取/classroom/teacher以前的全部同级节点,结果就是选全部的student节点 /classroom/teacher/preceding-sibling::*
选取/classroom中第二个stduent以后的全部同级节点 /classroom/student[2]/following-sibling::*
选取/classroom/teacher节点全部以前的节点(除其祖先外),不只仅是student节点,还有里面的子节点 /classroom/teacher/preceding::*
选取/classroom中第二个student以后的全部节点,结果就是选择了teacher节点及其子节点 /classroom/student[2]/following::*
选取student节点,单独使用没有什么意思 //stduent/self::*
选取/classroom/teacher/name节点下的全部属性 /classroom/teacher/name/attribute::*
XPath运算符示例分析
含义 实例
选取classroom元素的全部student元素 /classroom/student[age=19+1] /classroom/stduent[age=5*4] /classroom/student[age=21-1]
且其中的age元素的值须等于20 /classroom/student[age=40div2]
相似能够选取 大于、小于、不等于等操做
or 运算实例 /classroom/stduent[age<20 or age>25] .................age小于20或者大于25
and 运算实例 /classroom/stduent[age>20 and age<25] ..................age在20 到25 之间
mod 计算除法的余数
实例代码
from lxml import etree contentStream = open(r'xpathText.xml', 'rb') content = contentStream.read().decode('utf-8') root = etree.XML(content) print(content) print('-------') em = root.xpath('/classroom/student[2]/following::*') print(em[0].xpath('./name/text()'))#获取name标签中文本的内容 print(em[0].xpath('./name/@lang')) #获取name标签中属性名为lang的属性值
BeautifulSoup基础知识
建立BeautifulSoup对象的两种方式 1.经过字符串建立 soup=BeautifulSoup(htl_str,'lxml') 其中'lxml'表示指定的解析方式
2.经过文件建立 soup=BeautifulSoup(open('index.html'))
对象种类 四种 Tag、NavigableString、BeautifulSoup 、Comment
1)Tag
在html中每一个标签及其里面的内容就是一个Tag对象,如何抽取Tag呢?
soup.title抽取title soup.a 抽取a 利用soup+标记名查找的是再内容中第一个符合要求的标记
Tag中有两个最重要的属性:name和attributes.每一个Tag都有本身的名字,经过.name来获取
修改Tag的name,修改完成后将影响全部经过当前Beautiful Soup对象生成的HTML文档
html_str = """<html>
<head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p><p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1"><!-- 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>
</body>
</html>"""
soup = BeautifulSoup(html_str, 'lxml') # soup = BeautifulSoup(open(r'index.html','rb'),'lxml') print(soup.prettify()) #以格式化的形式输出文档的内容 print(soup.name) print(soup.title.name)#输出title的名称 soup.title.name = 'mytitle' #修改title的名称为mytitle print(soup.title) #title已经修改输出None print(soup.mytitle)#输出mytitle Tag
输出结果
整个文档的内容 [document] title None <mytitle>The Dormouse's story</mytitle>
获取Tag属性?<p class="title"><b>The Dormouse's story</b></p>Tag p中有一个属性class值为title,获取代码以下:
Tag属性值的修改相似于上述标签名的修改 soup.p['class']='myclass' 就把属性值title改成了myclass
# 获取Tag中的属性 和字典相似 print(soup.p['class']) print(soup.p.get('class'))
输出结果
['title'] ['title']
用于获取Tag全部属性的方法 print(soup.p.attrs)以字典的行书获取指定Tag的全部属性:属性值字典
输出格式以下
{'class': ['title']}
2)NavigableString 当已经获得了标记的内容,要想获取标记的内部文字怎么办呢?须要用到.string。
print(soup.b.string)#输出Tag对象b的内容 print(type(soup.b.string))#输出Tage对象b的内容的类型 其实就是NavigableString类型
输出结果
The Dormouse's story <class 'bs4.element.NavigableString'>
3)Beautiful Soup
Beautiful Soup对象表示的是一个文档的所有内容。大部分时候,能够把它看成Tag对象,是一个特殊的人Tag,实例以下
print(type(soup.name)) print(soup.name) print(soup.attrs)
输出结果
<class 'str'> [document] {}
4) Comment 文档的注释部分 ,示例以下
print(soup.a.string) print(type(soup.a.string))
输出结果
Elsie <class 'bs4.element.Comment'>
遍历文档
1)子节点
Tag中的.contents和.children是很是重要的,都是输出直接子节点,Tag的contents属性能够将Tag子节点以列表的方式输出:
print(soup.html.contents) print(soup.html.contents[1])#若是soup.html.contents[1].string会直接输出文档里的内容,具体解释看下面
输出结果
['\n', <head><mytitle>The Dormouse's story</mytitle></head>, '\n', <body> <p class="title"><b>The Dormouse's story</b></p><p class="story">Once upon a time there were three little sisters; and their names were <a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a> <a class="sister" href="http://example.com/lacie" id="link2"> <!--Lacie --> </a> and <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>; and they lived at the bottom of a well. </p><p class="story">……</p> </body>, '\n'] <head><mytitle>The Dormouse's story</mytitle></head>
Tag中children,其实.children返回的是一个生成器,能够对Tag的子节点进行循环
for child in soup.html.children: # 孩子结点递归循环 print(child)
输出结果:对于输出换行时,他要空两行,由于print自带换行
<head><mytitle>The Dormouse's story</mytitle></head> <body> <p class="title"><b>The Dormouse's story</b></p><p class="story">Once upon a time there were three little sisters; and their names were <a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a> <a class="sister" href="http://example.com/lacie" id="link2"> <!--Lacie --> </a> and <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>; and they lived at the bottom of a well. </p><p class="story">……</p> </body>
.descendants属性能够对全部tag的子孙节点进行递归循环:head中只有一个直接2节点title,但title也包含一个子节点:字符串'The Dormouse's story',
在这种状况下,字符串也属于<head>标记的子孙节点,
for child in soup.head.descendants: # 子孙节点递归循环 print(child)
输出结果
<mytitle>The Dormouse's story</mytitle> The Dormouse's story
如何获取标记的内容呢???这就涉及.string、.strings、stripped_strings三个属性
.string这个属性颇有特色:若是一个标记里面没有标记了,那么.string就会返回标记里面的内容。若是标记里面只有惟一
的一个标记了,那么.string也会返回最里面的内容。若是tag包含多个子节点,tag就没法肯定,string方法应该调用哪一个子节点的内容,.string的输出结果是None
print(soup.head.string) print(soup.mytitle.string) print(soup.html.string)
输出结果
The Dormouse's story The Dormouse's story None
.strings属性主要应用于tag中包含多个字符串的状况,能够进行循环遍历
for stri in soup.strings: print(repr(stri))
输出结果
'\n' "The Dormouse's story" '\n' '\n' "The Dormouse's story" 'Once upon a time there were three little sisters; and their names were\n ' '\n' '\n' '\n' '\n and\n ' 'Tillie' ';\n and they lived at the bottom of a well.\n' '……' '\n' '\n'
.stripped_strings属性能够去掉输出字符串中包含的空格或换行,示例以下
for stri in soup.stripped_strings: print(repr(stri))
输出结果
"The Dormouse's story" "The Dormouse's story" 'Once upon a time there were three little sisters; and their names were' 'and' 'Tillie' ';\n and they lived at the bottom of a well.' '……'
2)父节点
每一个Tag或者字符串都有父节点:被包含在某个Tag中。经过.parent能够获取某个元素的父节点
print soup.mytitle.parent 输出<head><title>........</title></head>
经过元素的.parents属性能够递归获得元素全部父辈节点,使用.parents方法遍历了<a>标记到根节点的全部节点
print(soup.a) for parent in soup.a.parents: if parent is None: print(parent) else: print(parent.name)
输出结果
<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a> p body html [document]
3)兄弟节点:能够理解为和本节点出在同一级上的节点,.next_sibling属性能够获取该节点的下一个兄弟节点,.previous_sibling则与之相反,
若是节点不存在,则返回None
能够经过.next_siblings和.previous_siblings来迭代全部的兄弟节点
4)先后节点
先后节点须要使用.next_element、previous_element这两个属性,他针对全部节点,不分层次,例如<head><title>The Dormouse‘s story</title></head>
中的下一个节点是title
若是想遍历全部的前节点或者后节点,经过.next_elements和previous_elements的迭代器就能够向前或向后访问文档的解析内容
for elem in soup.html.next_elements: #有点像深度优先遍历 print(repr(elem))
输出结果
'\n' <head><mytitle>The Dormouse's story</mytitle></head> <mytitle>The Dormouse's story</mytitle> "The Dormouse's story" '\n' <body> <p class="title"><b>The Dormouse's story</b></p><p class="story">Once upon a time there were three little sisters; and their names were <a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a> <a class="sister" href="http://example.com/lacie" id="link2"> <!--Lacie --> </a> and <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>; and they lived at the bottom of a well. </p><p class="story">……</p> </body> '\n' <p class="title"><b>The Dormouse's story</b></p> <b>The Dormouse's story</b> "The Dormouse's story" <p class="story">Once upon a time there were three little sisters; and their names were <a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a> <a class="sister" href="http://example.com/lacie" id="link2"> <!--Lacie --> </a> and <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>; and they lived at the bottom of a well. </p> 'Once upon a time there were three little sisters; and their names were\n ' <a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a> ' Elsie ' '\n' <a class="sister" href="http://example.com/lacie" id="link2"> <!--Lacie --> </a> '\n' 'Lacie ' '\n' '\n and\n ' <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a> 'Tillie' ';\n and they lived at the bottom of a well.\n' <p class="story">……</p> '……' '\n' '\n'
搜索文档
只介绍find_all()方法,其它方法相似
函数原型
find_all(name,attrs,recursive,text,**kwargs)
1)name参数
name参数能够查找全部名字为name的标记,字符对象会被自动忽略掉。name参数取值能够是字符串、正则表达式、列表、True和方法
字符串案例 用于查找文档中全部的<b>标记 ,返回值为列表:
print(soup.find_all('b')) #输出结果 [<b>The Dormouse's story</b>]
传入正则表达式做为参数,会经过正则表达式的match()来匹配内容。下面列出全部以b开头的标记,这表示<body>和<b>标记
for tag in soup.find_all(re.compile('^b')): print(tag.name) #输出结果 body b
传入列表
print(soup.find_all(['a','b']))//找到文档中全部的<a>标记和<b>标记
传入True,True能够匹配任何值,会查找全部的tag ,但不会返回字符串节点
for tag in soup.find_all(True): print(tag.name) #输出结果 html head mytitle body p b p a a a p
若是没有合适过滤器,那么还能够定义一个方法,方法只接受一个元素参数Tag节点,若是这个方法返回?True表示当前元素匹配而且被找到
,若是不是则返回False,好比过滤包含class属性,也包含id属性的元素
def hasClass_Id(tag): return tag.has_attr('class') and tag.has_attr('id') print(soup.find_all(hasClass_Id)) #输出结果 [<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>]
2)kwargs参数
kwargs参数就是python中的keyword参数 ,若是一个指定名字的参数不是搜索内置的参数名,搜索时会把该参数看成指定名字Tag的属性来搜索
。搜索指定名字的属性时可使用的参数值包括字符串、正则表达式、列表、True
传入字符串 print(soup.find_all(id='link2')) 会搜索每一个tag的id属性
传入正则表达式 print(soup.find_all(href=re.compile('elsie')))搜索href属性中含有‘elsie’的tag
True print(soup.find_all(id=True)) 文档树中查找全部包含id属性的Tag,不管id的值是什么:
若是想用 class过滤·,但class是python的关键字,须要在class后main加个下划线:
soup.find_all('a',class_='sister')
有些tag属性在搜索中不能使用,好比HTML5中的data-*属性 能够经过find_all()方法的attrs参数定义一个字典参数来搜索包含特殊属性的tag
,
data_soup = BeautifulSoup('<div data-foo="value">foo!</div>', 'lxml') print(data_soup.find_all(attrs={"data-foo": "value"})) # data_soup.find_all(data - foo = 'value') #报错 特殊属性不能这样处理 #输出结果 [<div data-foo="value">foo!</div>]
3)text参数
经过text参数能够搜索文档中的字符串内容。与name参数的可选值同样,text参数接受字符、正则表达式、列表、True
print soup.find_all(text=["Tillie", "Elsie", "Lacie"])
print soup.find_all(text=re.compile("Dormouse"))输出结果
[u'Elsie', u'Lacie', u'Tillie']
[u"The Dormouse's story", u"The Dormouse's story"]
4)limit参数
find_all()方法返回所有的搜索结构,若是文档树很大那么搜索会很慢2.若是咱们不须要所有结果,可使用limit参数限制返回结果的数量
soup.find_all('a',limit=2)值返回两条结果
5)recursive参数
调用tag的find_all()方法是,Beautiful Soup会检索当前tag的全部子孙节点,若是只想检索tag的直接子节点,可使用参数
recusive=False
print(soup.find_all('mytitle')) print(soup.find_all('mytitle', recursive=False)) #输出结果 [<mytitle>The Dormouse's story</mytitle>] []