Python HTML解析器BeautifulSoup用法实例详解【爬虫解析器】
本文实例讲述了PythonHTML解析器BeautifulSoup用法。分享给大家供大家参考,具体如下:
BeautifulSoup简介
我们知道,Python拥有出色的内置HTML解析器模块——HTMLParser,然而还有一个功能更为强大的HTML或XML解析工具——BeautifulSoup(美味的汤),它是一个第三方库。简单来说,BeautifulSoup最主要的功能是从网页抓取数据。本文我们来感受一下BeautifulSoup的优雅而强大的功能吧!
BeautifulSoup安装
BeautifulSoup3目前已经停止开发,推荐在现在的项目中使用BeautifulSoup4,不过它已经被移植到bs4了,也就是说导入时我们需要importbs4。可以利用pip或者easy_install两种方法来安装。下面采用pip安装。
pipinstallbeautifulsoup4 pipinstalllxml
建议同时安装"lxml"模块,BeautifulSoup支持Python标准库中的HTML解析器(HTMLParser),还支持一些第三方的解析器,如果我们不安装它,则Python会使用Python默认的解析器,lxml解析器更加强大,速度更快,推荐安装。
创建对象
安装后,创建对象:
soup=BeautifulSoup(markup='html文件','lxml')
格式化输出:
soup.prettify()
BeautifulSoup四大对象类型
BeautifulSoup将复杂HTML文档转换成一个复杂的树形结构,每个节点都是Python对象,所有对象可以归纳为4种:
- Tag(标签)
- NavigableString(内容)
- BeautifulSoup(文档)
- Comment(注释)
1.Tag类型
即HTML的整个标签,如获取
printsoup.title #TheDormouse'sstory
Tag有两个重要属性:name,attrs。
name
即HTML的标签名称:
printsoup.name #[document] printsoup.head.name #head
attrs
即HTML的标签属性字典:
printsoup.p.attrs #{'class':['title'],'name':'dromouse'}
如果想要单独获取某个属性:
printsoup.p['class'] #['title']
2.NavigableString类型
既然我们已经得到了整个标签,那么问题来了,我们要想获取标签内部的文字内容怎么办呢?很简单,用string即可:
printsoup.p.string #TheDormouse'sstory
3.BeautifulSoup类型
BeautifulSoup对象表示的是一个文档的全部内容.:
printsoup.name #[document]
4.Comment类型
HTML的注释内容,注意的是,不包含注释符号。我们首先判断它的类型,是否为Comment类型,然后再进行其他操作,如打印输出:
iftype(soup.a.string)==bs4.element.Comment: printsoup.a.string #
遍历文档树
1.子节点
contents
获取所有子节点,返回列表:
printsoup.head.contents #[TheDormouse'sstory ]
children
获取所有子节点,返回列表生成器:
printsoup.head.children ###需要遍历 forchildinsoup.body.children: printchild ##结果 TheDormouse'sstory Onceuponatimetherewerethreelittlesisters;andtheirnameswere , Lacieand Tillie; andtheylivedatthebottomofawell. ...
2.节点内容
string
返回单个文本内容。如果一个标签里面没有标签了,那么string就会返回标签里面的内容。如果标签里面只有唯一的一个标签了,那么string也会返回最里面的内容。如果tag包含了多个子节点,tag就无法确定,string方法应该调用哪个子节点的内容,string的输出结果是None。例如:
printsoup.head.string printsoup.title.string #TheDormouse'sstory #TheDormouse'sstory printsoup.html.string #None
strings
返回多个文本内容,且包含空行和空格。
stripped_strings
返回多个文本内容,且不包含空行和空格:
forstringinsoup.stripped_strings: print(repr(string)) #u"TheDormouse'sstory" #u"TheDormouse'sstory" #u'Onceuponatimetherewerethreelittlesisters;andtheirnameswere' #u'Elsie' #u',' #u'Lacie' #u'and' #u'Tillie' #u';\nandtheylivedatthebottomofawell.' #u'...'
get_text()方法
返回当前节点和子节点的文本内容。
frombs4importBeautifulSoup html_doc="""TheDormouse'sstory TheDormouse'sstory Onceuponatimetherewerethreelittlesisters;andtheirnameswere Elsie, Lacieand Tillie; andtheylivedatthebottomofawell. ... """ soup=BeautifulSoup(markup=html_doc,features='lxml') node_p_text=soup.find('p',class_='story').get_text()#注意class_带下划线 print(node_p_text) #结果 Onceuponatimetherewerethreelittlesisters;andtheirnameswere Elsie, Lacieand Tillie; andtheylivedatthebottomofawell.
3.父节点
parent
返回某节点的直接父节点:
p=soup.p printp.parent.name #body
parents
返回某节点的所有父辈及以上辈的节点:
content=soup.head.title.string forparentincontent.parents: printparent.name ##结果 title head html [document]
4.兄弟节点
next_sibling
next_sibling属性获取该节点的下一个兄弟节点,结果通常是字符串或空白,因为空白或者换行也可以被视作一个节点。
previous_sibling
previous_sibling属性获取该节点的上一个兄弟节点。
printsoup.p.next_sibling #实际该处为空白 printsoup.p.prev_sibling #None没有前一个兄弟节点,返回None printsoup.p.next_sibling.next_sibling #Onceuponatimetherewerethreelittlesisters;andtheirnameswere # , # Lacieand # Tillie; #andtheylivedatthebottomofawell. #下一个节点的下一个兄弟节点是我们可以看到的节点
next_siblings、previous_siblings
迭代获取全部兄弟节点。
5.前后节点
next_element、previous_element
不是针对于兄弟节点,而是在于所有节点,不分层次的前一个和后一个节点。
next_elements、previous_elements
迭代获取所有前和后节点。
搜索文档树
1.find_all(name=None,attrs={},recursive=True,text=None,limit=None,**kwargs)
find_all()方法搜索当前tag的所有tag子节点,并判断是否符合过滤器的条件。
参数说明
name参数
name参数很强大,可以传多种方式的参数,查找所有名字为name的tag,字符串对象会被自动忽略掉。
(a)传标签名
最简单的过滤器是标签名。在搜索方法中传入一个标签名参数,BeautifulSoup会查找与标签名完整匹配的内容,下面的例子用于查找文档中所有的标签:
printsoup.find_all('a') #[, Lacie, Tillie]
返回结果列表中的元素仍然是BeautifulSoup对象。
(b)传正则表达式
如果传入正则表达式作为参数,BeautifulSoup会通过正则表达式的match()来匹配内容。下面例子中找出所有以b开头的标签,这表示
importre fortaginsoup.find_all(re.compile("^b")): print(tag.name) #body #b
(c)传列表
如果传入列表参数,BeautifulSoup会将与列表中任一元素匹配的内容返回。下面代码找到文档中所有标签和标签:
soup.find_all(["a","b"]) #[TheDormouse'sstory, #Elsie, # Lacie, # Tillie]
(d)传True
True可以匹配任何值,下面代码查找到所有的tag,但是不会返回字符串节点:
fortaginsoup.find_all(True): print(tag.name) #html #head #title #body #p #b #p #a #a
(e)传函数
如果没有合适过滤器,那么还可以定义一个方法,方法只接受一个元素参数。如果这个方法返回True表示当前元素匹配并且被找到,如果不是则反回False:
defhas_class_but_no_id(tag): returntag.has_attr('class')andnottag.has_attr('id') soup.find_all(has_class_but_no_id) #[TheDormouse'sstory, # Onceuponatimetherewere..., # ...]
keyword参数
注意的是,如果一个指定名字的参数不是搜索内置的参数名,搜索时会把该参数当作指定名字tag的属性来搜索,如果包含一个名字为id的参数,BeautifulSoup会搜索每个tag的”id”属性:
soup.find_all(id='link2') #[Lacie]
如果传入href参数,BeautifulSoup会搜索每个tag的"href"属性:
soup.find_all(href=re.compile("elsie")) #[Elsie]
使用多个指定名字的参数可以同时过滤tag的多个属性:
soup.find_all(href=re.compile("elsie"),id='link1') #[three]
在这里我们想用class过滤,不过class是python的关键词,这怎么办?加个下划线就可以:
soup.find_all("a",class_="sister") #[Elsie, # Lacie, # Tillie]
attrs参数
有些tag属性在搜索不能使用,比如HTML5中的"data-*"自定义属性:
data_soup=BeautifulSoup('foo!
text参数
通过text参数可以搜搜文档中的字符串内容。与name参数的可选值一样,text参数接受字符串、正则表达式、列表、True。
soup.find_all(text="Elsie") #[u'Elsie'] soup.find_all(text=["Tillie","Elsie","Lacie"]) #[u'Elsie',u'Lacie',u'Tillie'] soup.find_all(text=re.compile("Dormouse"))#模糊查找 [u"TheDormouse'sstory",u"TheDormouse'sstory"]
limit参数
find_all()方法返回全部的搜索结构,如果文档树很大那么搜索会很慢。如果我们不需要全部结果,可以使用limit参数限制返回结果的数量。效果与SQL中的limit关键字类似,当搜索到的结果数量达到limit的限制时,就停止搜索返回结果。
soup.find_all("a",limit=2) #[Elsie, # Lacie]
recursive参数
调用tag的find_all()方法时,BeautifulSoup会检索当前tag的所有子孙节点,如果只想搜索tag的直接子节点,可以使用参数recursive=False。
soup.html.find_all("title") #[TheDormouse'sstory ] soup.html.find_all("title",recursive=False) #[]
2.find(name,attrs,recursive,text,**kwargs)
它与find_all()方法唯一的区别是find_all()方法的返回结果是值包含一个元素的列表,而find()方法直接返回结果。
3.find_parents()和find_parent()
find_all()和find()只搜索当前节点的所有子节点,孙子节点等。find_parents()和find_parent()用来搜索当前节点的父辈节点,搜索方法与普通tag的搜索方法相同,搜索文档搜索文档包含的内容。
4.find_next_siblings()和find_next_sibling()
这2个方法通过.next_siblings属性对当tag的所有后面解析的兄弟tag节点进行迭代,find_next_siblings()方法返回所有符合条件的后面的兄弟节点,find_next_sibling()只返回符合条件的后面的第一个tag节点。
5.find_previous_siblings()和find_previous_sibling()
这2个方法通过.previous_siblings属性对当前tag的前面解析的兄弟tag节点进行迭代,find_previous_siblings()方法返回所有符合条件的前面的兄弟节点,find_previous_sibling()方法返回第一个符合条件的前面的兄弟节点。
6.find_all_next()和find_next()
这2个方法通过.next_elements属性对当前tag的之后的tag和字符串进行迭代,find_all_next()方法返回所有符合条件的节点,find_next()方法返回第一个符合条件的节点。
7.find_all_previous()和find_previous()
这2个方法通过.previous_elements属性对当前节点前面的tag和字符串进行迭代,find_all_previous()方法返回所有符合条件的节点,find_previous()方法返回第一个符合条件的节点。
CSS选择器
我们在写CSS时,标签名不加任何修饰,类名前加点,id名前加#,在这里我们也可以利用类似的方法来筛选元素,用到的方法是soup.select(),返回类型是list。
通过标签名查找
printsoup.select('title') #[TheDormouse'sstory ] printsoup.select('a') #[, Lacie, Tillie] printsoup.select('b') #[TheDormouse'sstory]
通过类名查找
printsoup.select('.sister') #[, Lacie, Tillie]
通过id名查找
printsoup.select('#link1') #[]
组合查找
组合查找即和写class文件时,标签名与类名、id名进行的组合原理是一样的,例如查找p标签中,id等于link1的内容,二者需要用空格分开。
printsoup.select('p#link1') #[]
直接子标签查找:
printsoup.select("head>title") #[TheDormouse'sstory ]
属性查找
查找时还可以加入属性元素,属性需要用中括号括起来,注意属性和标签属于同一节点,所以中间不能加空格,否则会无法匹配到。
printsoup.select('a[class="sister"]') #[, Lacie, Tillie] printsoup.select('a[href="http://example.com/elsie"rel="externalnofollow"rel="externalnofollow"rel="externalnofollow"rel="externalnofollow"rel="externalnofollow"rel="externalnofollow"rel="externalnofollow"rel="externalnofollow"rel="externalnofollow"rel="externalnofollow"rel="externalnofollow"rel="externalnofollow"rel="externalnofollow"rel="externalnofollow"rel="externalnofollow"rel="externalnofollow"rel="externalnofollow"rel="externalnofollow"]') #[ ]
同样,属性仍然可以与上述查找方式组合,不在同一节点的空格隔开,同一节点的不加空格:
printsoup.select('pa[href="http://example.com/elsie"rel="externalnofollow"rel="externalnofollow"rel="externalnofollow"rel="externalnofollow"rel="externalnofollow"rel="externalnofollow"rel="externalnofollow"rel="externalnofollow"rel="externalnofollow"rel="externalnofollow"rel="externalnofollow"rel="externalnofollow"rel="externalnofollow"rel="externalnofollow"rel="externalnofollow"rel="externalnofollow"rel="externalnofollow"rel="externalnofollow"]') #[]
以上的select方法返回的结果都是列表形式,可以遍历形式输出,然后用string或get_text()方法来获取它的内容:
soup=BeautifulSoup(html,'lxml') printtype(soup.select('title')) printsoup.select('title')[0].get_text() fortitleinsoup.select('title'): printtitle.get_text()
更多关于Python相关内容可查看本站专题:《PythonSocket编程技巧总结》、《Python正则表达式用法总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》
希望本文所述对大家Python程序设计有所帮助。