python Beautifulsoup运用

来源:互联网 发布:python re模块 小甲鱼 编辑:程序博客网 时间:2024/06/04 08:58

python3中的Beautifulsoup模块是负责用来解析HTML的,相似的还有lxml html解析器,但是这个需要安装C语言库,所以一般用Beautifulsoup来解析HTML。
https://www.crummy.com/software/BeautifulSoup/bs4/doc/index.zh.html

1.创建Beautiful Soup对象
首先先导入bs4库

from bs4 import BeautifulSoup

然后创建一些字符串,里面类似于HTML文档:

HTML= """<html><head><title>The Dormouse's story</title></head><body><p class="title" name="dromouse"><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>

创建beautifulsoup对象

soup=BeautifulSoup(html,'html.parser')print(soup.prettify())

运行上面 的语句,我们将会得到HTML的格式化输出。
2.四大对象种类
Beautiful Soup将HTML文档转换成一个复杂的树形结构,每个节点都是python对象,所有对象可以归纳为4种:

  • Tag
  • NavigableString
  • BeautifulSoup
  • Comment
    2.1 Tag
    Tag指的是HTML中一个个标签,例如
<title>The Dou's story<title>

上面的title以及里面的内容就是HTML的一个标签,beautiful soup 可以很方便地获取Tags
例如:

print(soup.title)print(soup.p)print(soup.head)print(soup.a)

上面代码利用soup加上标签名来获取这些标签,但是它一般只会查找出所有内容中第一个符合要求的标签,后面将会介绍如何去查询所有的标签。
对于Tag来说,它有两个重要的属性,name和attrs,下面来看看。
name

print(soup.name)print(soup.head.name)print(soup.title.name)

其中soup的name就是【document】
attrs

print(soup.p.attrs)

运行上面的句子会得到#{‘class’:[title],’name’:’dromouse’},就是将p标签的所有属性都打印出来,得到的类型是一个字典。
如果我们想要单独获取某个属性,可以这样,例如我们获取它的class叫什么

print(soup.p['class'])#['title']

还可以用get方法,传入属性的名称

print(soup.p.get('class'))#title

我们甚至可以对这些属性以内容进行修改,例如:

soup.p['class']='newClass'print(soup.p)#<p clas='newClass'......

2.2 NavigableString
既然我们已经得到了标签的内容,那么问题来了,想要获取标签的内部文字怎么办?

print(soup.p.string)#The Dormouse's story

即用.string语句来实现获取内部文字的功能,它本省的类型是一个NavigableString,意思是 可以遍历的字符串

print(type(soup.p.string))

会得到NavigableString这个类型
2.3 BeautifulSoup
一般BeautifulSoup对象表示的是一个文档的全部内容,大部分时候可以将它当做Tag对象,是一个特殊的tag,下面分别获取它的类型,名称以及属性:

print(type(soup.name))#<type 'unicode'>print(soup.name)#[document]print(soup.attrs)#{} 空字典

2.4 Comment
comment对象是一个特殊类型的NavigableString对象,输出的内容仍然不包括注释符号,找一个带注释的标签

print(soup.a)print(soup.a.string)print(type(soup.a.string))

结果:

<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a> Elsie <class 'bs4.element.Comment'>

a里面的内容实际上是注释,但是如果我们利用.string来输出它的内容,就会发现已经把注释给去掉了,所以一般判断它的类型,看是否为Comment类型

3.遍历文档树
3.1 直接子节点
.contents .children属性
.contents
tag的.contents属性将tag的子节点以列表的方式输出

print(soup.head.contents)#[<title>The Dormouse's story</title>]

输出的方式为列表,我们可以用列表索引来获取它的某一个元素

print(soup.head.contents[0])#<title>The Dormouse's story</title>

.children
它返回的不是一个list,但是我们可以便利获取所有的子节点

for x in soup.body.children:    print(x)
<p class="title" name="dromouse"><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

3.2 所有的子孙节点
.descendants
.descendants属性可以对所有tag 的子孙节点进行递归循环,只需要遍历获取其中的内容

for x in soup.descendants:    print(x)

从运行结果可以发现,所有的节点都被打印出来了,先生成最外层的HTML标签,其次从head标签一个个剥离

html><head><title>The Dormouse's story</title></head><body><p class="title" name="dromouse"><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>,

3.3 节点内容
.string属性
如果tag包含了多个子节点,tag就无法确定,string方法应该刁颖哪个子节点的内容,string的输出为none
3.4 多个内容
.strings属性
获取多个内容,需要遍历获取,例如:

for string in soup.strings:    print(repr(string))     # u"The Dormouse's story"    # u'\n\n'    # u"The Dormouse's story"    # u'\n\n'    # u'Once upon a time there were three little sisters; and their names were\n'    # u'Elsie'    # u',\n'    # u'Lacie'    # u' and\n'    # u'Tillie'    # u';\nand they lived at the bottom of a well.'    # u'\n\n'    # u'...'    # u'\n'

.stripped_strings
输出的字符串中包含了很多空格或者空行,使.stripped_strings可以去除多余的空白内容

for string in soup.stripped_string;    print(repr(string))    # u"The Dormouse's story"    # u"The Dormouse's story"    # u'Once upon a time there were three little sisters; and their names were'    # u'Elsie'    # u','    # u'Lacie'    # u'and'    # u'Tillie'    # u';\nand they lived at the bottom of a well.'    # u'...'

3.5 父节点
.parent 属性

print(soup.p.parent.name)#bodyprint(soup.head.title.string.parent.name)#title

3.6全部父节点
.parents属性
需要递归得到元素的所有父节点,例如:

content=soup.head.title.stringfor parent in content.parents:    print(parent.name)
titleheadhtml[document]

3.7 兄弟节点
.next_sibing .previous_sibling
兄弟节点可以理解为和本节点处在同一级的节点:

print(soup.p.next_sibling)print(soup.p.prev_sibing)print(soup.p.next_sibling.next_sibing)

前面两个返回none,后面返回下两个的兄弟节点

3.8 全部兄弟节点
.next_siblings .previous_sibling属性
可以对当前节点的兄弟节点迭代输出

for sibling in soup.a.next_sublings:    print(repr(sibling))

3.9 前后节点
.next_element .previous_element属性
与兄弟节点不同,并不是针对兄弟节点,而是在所有节点,部分层次,比如head节点为:

<head><title>The Dormouse's story</title></head>

那么它的下一个节点就是title,它是不分层次的:

print(soup.head.next_elemengt)#<title>The Dormouse's story</title>

3.10 前后所有节点
.next_elements .previous_elements属性

需要遍历
4.搜索文档树
4.1find_all(name,attrs,recursive,text,**kwargs)
find_all()方法可以搜索当前tag的所有tag子节点并且判断是否符合过滤器的条件

  • name参数
    name参数可以查找所有名字为xx的tag,字符串对象会被自动忽略掉
    a.传字符串
    最简单的过滤器是字符串,在搜索方法中传入一个字符串参数,Beautiful Soup会查找与字符串完整匹配的内容:
print(soup.find_all('b'))#[<b>The Dormouse's story</b>]

b.传正则表达式
如果传入正则表达式作为参数,Beautiful Soup会通过正则表达式的match()来匹配内容。下面例子中找出所有以b开头的标签,这表示标签都应该被找到

import refor tag in soup.find_all(re.compile('^b')    print(tag.name)#body#b

c.传列表
如果传入列表,Beautiful Soup会将与列表中任一元素匹配的内容返回:

print(soup.find_all(['a','b']))# [<b>The Dormouse's story</b>,#  <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>]

D.传true
True可以匹配任何值,下面代码查找所有的tag,但是不会返回字符串节点

for tag in soup.find_all(True):    print(tag.name)# html# head# title# body# p# b# p# a# a

E.传方法
如果没有适合过滤器,那么还可以定义一个方法,这个方法只接受一个元素参数,如果这个方法返回True表示当前元素匹配并且被找到,如果不是则返回False
下面方法校验了当前元素,如果包含class属性却不包含id
属性,那么返回True:

def has_class_but_no_id(tag):    return tag.has_attr('class') and not tag.has_attr('id')

将这个方法作为参数传入find_all()犯法,将得到所有

标签:

print(soup.find_all(has_class_but_no_id))# [<p class="title"><b>The Dormouse's story</b></p>,#  <p class="story">Once upon a time there were...</p>,#  <p class="story">...</p>]
  • keyword参数
print(soup.find_all(id='link2'))# [<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]

如果传入href参数,Beautiful Soup会搜索每个tag的“href”属性:

print(soup.find_all(href=re.compile('elsie'))# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>]

使用多个指定名字的参数可以同时过滤tag的多个属性:

print(soup.find_all(href=re.compile('elsie),id='link1'))# [<a class="sister" href="http://example.com/elsie" id="link1">three</a>]

在这里我们想用class过滤,但是class是python的关键词,这怎么办?价格下划线就可以了:

print(soup.find_all('a',class_=sister'))# [<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>]

有些tag属性在搜索不能使用,比如HTML5中的data-*属性:

data_soup=BeautifulSoup('<div data-foo='value'>foo!</div>)data_soup.find_all(data-foo='value')# SyntaxError: keyword can't be an expression

但是可以通过find_all()方法的attrs参数定义一个字典参数来搜索包含特殊属性的tag

data_soup.find_all(attrs={'data-foo':'value'})# [<div data-foo="value">foo!</div>]
  • text参数
    通过text参数可以搜搜文档中的字符串内容,与name参数的可选值一样,text参数接受字符串、正则表达式、列表、True:
print(soup.find_all(text='Elsie')#[u'Elsie']print(soup.find_all(text=['Tittie','Elsie','Lacie'])#[u'Elsie',u'Lacie',u'Tillie']print(soup.find_all(text=re.compile('Dormouse'))[u'The Dormouse's story',u'The Dormouse's story']
  • limit参数
    find_all()方法返回全部的搜索结构,如果文档树和拿到,那么搜索会很慢,可以使用limit参数限制返回结果的数量:
print(soup.find_all('a',limit=2))# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,#  <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]

-recursive参数
调用tag的 find_all() 方法时,Beautiful Soup会检索当前tag的所有子孙节点,如果只想搜索tag的直接子节点,可以使用参数 recursive=False.

soup.html.find_all("title")# [<title>The Dormouse's story</title>]soup.html.find_all("title", recursive=False)# []

find(name,attrs,recursive,text,**kwargs)
find_parents()和find_parent()
find_next_sibling()和find_next_sibling()
find_previous_siblings()和find_previous_sibling()
find_all_next()和find_next()
find_all_previous()和find_previous()

5.CSS选择器
我们在写 CSS 时,标签名不加任何修饰,类名前加点,id名前加 #,在这里我们也可以利用类似的方法来筛选元素,用到的方法是 soup.select(),返回类型是 list

  1. 通过标签名查找
print(soup.select('title')#[<title>The Dormouse's story</title>]print(soup.select('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>]print(soup.select('b'))#[<b>The Dormouse's story</b>]

2.通过类名查找

print(soup.select('.sister'))#[<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>]

3.通过id名查找

print(soup.select('#link1'))#[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>]

4.组合查找
组合查找即和写class文件时,标签名与类名、id名进行的组合原理是一样 的,例如查找p标签中,id等于link1的内容,二者需要空格分开

print(soup.select('p #link1'))#[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>]

直接子标签查找

print(soup.select('head>title')#[<title>The Dormouse's story</title>]

5.属性查找
查找时还可以加入属性元素,属性需要用中括号括起来,注意属性和标签属于同一节点,属于中间不能加空格,否则会无法匹配到。

print(soup.select('a[class='sisiter']))#[<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>print(soup.select('a['href='http://example.com/elsie'])#[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>]

同样,属性仍然可以与上诉查找方式组合,不在同一节点的空格隔开,同一节点的不加空格

print(soup.select('p a[href='http://example.com/elsie']')#[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>

以上的select方法返回的结果都是列表形式,可以遍历形式输出,然后用get_text()方法来获取它的内容

soup=BeautifulSoup(html,'lxml')print(type(soup.select('title'))print(soup.select('title')[0].get_text()for title in soup.select('title'):    print(title.get_text())
原创粉丝点击