系统城装机大师 - 固镇县祥瑞电脑科技销售部宣传站!

当前位置:首页 > 脚本中心 > python > 详细页面

Python爬虫库BeautifulSoup的介绍与简单使用实例

时间:2020-01-27来源:系统城作者:电脑系统城

BeautifulSoup是一个可以从HTML或XML文件中提取数据的Python库,本文为大家介绍下Python爬虫库BeautifulSoup的介绍与简单使用实例其中包括了,BeautifulSoup解析HTML,BeautifulSoup获取内容,BeautifulSoup节点操作,BeautifulSoup获取CSS属性等实例

一、介绍

BeautifulSoup库是灵活又方便的网页解析库,处理高效,支持多种解析器。利用它不用编写正则表达式即可方便地实现网页信息的提取。

Python常用解析库

 

解析器 使用方法 优势 劣势
Python标准库 BeautifulSoup(markup, “html.parser”) Python的内置标准库、执行速度适中 、文档容错能力强 Python 2.7.3 or 3.2.2)前的版本中文容错能力差
lxml HTML 解析器 BeautifulSoup(markup, “lxml”) 速度快、文档容错能力强 需要安装C语言库
lxml XML 解析器 BeautifulSoup(markup, “xml”) 速度快、唯一支持XML的解析器 需要安装C语言库
html5lib BeautifulSoup(markup, “html5lib”) 最好的容错性、以浏览器的方式解析文档、生成HTML5格式的文档 速度慢、不依赖外部扩展

 

二、快速开始

给定html文档,产生BeautifulSoup对象


 
  1. from bs4 import BeautifulSoup
  2. html_doc = """
  3. <html><head><title>The Dormouse's story</title></head>
  4. <body>
  5. <p class="title">The Dormouse's story</p>
  6.  
  7. <p class="story">Once upon a time there were three little sisters; and their names were
  8. <a href="http://example.com/elsie" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="sister" id="link1">Elsie</a>,
  9. <a href="http://example.com/lacie" rel="external nofollow" rel="external nofollow"rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow"class="sister" id="link2">Lacie</a> and
  10. <a href="http://example.com/tillie" rel="external nofollow" rel="external nofollow"rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow"rel="external nofollow" class="sister" id="link3">Tillie</a>;
  11. and they lived at the bottom of a well.</p>
  12.  
  13. <p class="story">...</p>
  14. """
  15. soup = BeautifulSoup(html_doc,'lxml')

输出完整文本


 
  1. print(soup.prettify())

 
  1. <html>
  2. <head>
  3. <title>
  4. The Dormouse's story
  5. </title>
  6. </head>
  7. <body>
  8. <p class="title">
  9.  
  10. The Dormouse's story
  11.  
  12. </p>
  13. <p class="story">
  14. Once upon a time there were three little sisters; and their names were
  15. <a class="sister" href="http://example.com/elsie" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="link1">
  16. Elsie
  17. </a>
  18. ,
  19. <a class="sister" href="http://example.com/lacie" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="link2">
  20. Lacie
  21. </a>
  22. and
  23. <a class="sister" href="http://example.com/tillie" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="link3">
  24. Tillie
  25. </a>
  26. ;
  27. and they lived at the bottom of a well.
  28. </p>
  29. <p class="story">
  30. ...
  31. </p>
  32. </body>
  33. </html>

浏览结构化数据


 
  1. print(soup.title) #<title>标签及内容
  2. print(soup.title.name) #<title>name属性
  3. print(soup.title.string) #<title>内的字符串
  4. print(soup.title.parent.name) #<title>的父标签name属性(head)
  5. print(soup.p) # 第一个<p></p>
  6. print(soup.p['class']) #第一个<p></p>的class
  7. print(soup.a) # 第一个<a></a>
  8. print(soup.find_all('a')) # 所有<a></a>
  9. print(soup.find(id="link3")) # 所有id='link3'的标签

 
  1. <title>The Dormouse's story</title>
  2. title
  3. The Dormouse's story
  4. head
  5. <p class="title">The Dormouse's story</p>
  6. ['title']
  7. <a class="sister" href="http://example.com/elsie" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="link1">Elsie</a>
  8. [<a class="sister" href="http://example.com/elsie" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="link1">Elsie</a>, <a class="sister"href="http://example.com/lacie" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow"id="link2">Lacie</a>, <a class="sister" href="http://example.com/tillie" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="link3">Tillie</a>]
  9. <a class="sister" href="http://example.com/tillie" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="link3">Tillie</a>

找出所有标签内的链接


 
  1. for link in soup.find_all('a'):
  2. print(link.get('href'))

 
  1. http://example.com/elsie
  2. http://example.com/lacie
  3. http://example.com/tillie

获得所有文字内容


 
  1. print(soup.get_text())

 
  1. The Dormouse's story
  2.  
  3. The Dormouse's story
  4. Once upon a time there were three little sisters; and their names were
  5. Elsie,
  6. Lacie and
  7. Tillie;
  8. and they lived at the bottom of a well.
  9. ...

自动补全标签并进行格式化


 
  1. html = """
  2. <html><head><title>The Dormouse's story</title></head>
  3. <body>
  4. <p class="title" name="dromouse">The Dormouse's story</p>
  5. <p class="story">Once upon a time there were three little sisters; and their names were
  6. <a href="http://example.com/elsie" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="sister" id="link1"><!-- Elsie --></a>,
  7. <a href="http://example.com/lacie" rel="external nofollow" rel="external nofollow"rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow"class="sister" id="link2">Lacie</a> and
  8. <a href="http://example.com/tillie" rel="external nofollow" rel="external nofollow"rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow"rel="external nofollow" class="sister" id="link3">Tillie</a>;
  9. and they lived at the bottom of a well.</p>
  10. <p class="story">...</p>
  11. """
  12. from bs4 import BeautifulSoup
  13. soup = BeautifulSoup(html, 'lxml')#传入解析器:lxml
  14. print(soup.prettify())#格式化代码,自动补全
  15. print(soup.title.string)#得到title标签里的内容

标签选择器

选择元素


 
  1. html = """
  2. <html><head><title>The Dormouse's story</title></head>
  3. <body>
  4. <p class="title" name="dromouse">The Dormouse's story</p>
  5. <p class="story">Once upon a time there were three little sisters; and their names were
  6. <a href="http://example.com/elsie" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="sister" id="link1"><!-- Elsie --></a>,
  7. <a href="http://example.com/lacie" rel="external nofollow" rel="external nofollow"rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow"class="sister" id="link2">Lacie</a> and
  8. <a href="http://example.com/tillie" rel="external nofollow" rel="external nofollow"rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow"rel="external nofollow" class="sister" id="link3">Tillie</a>;
  9. and they lived at the bottom of a well.</p>
  10. <p class="story">...</p>
  11. """
  12. from bs4 import BeautifulSoup
  13. soup = BeautifulSoup(html, 'lxml')#传入解析器:lxml
  14. print(soup.title)#选择了title标签
  15. print(type(soup.title))#查看类型
  16. print(soup.head)

获取标签名称


 
  1. from bs4 import BeautifulSoup
  2. soup = BeautifulSoup(html, 'lxml')#传入解析器:lxml
  3. print(soup.title.name)

获取标签属性


 
  1. from bs4 import BeautifulSoup
  2. soup = BeautifulSoup(html, 'lxml')#传入解析器:lxml
  3. print(soup.p.attrs['name'])#获取p标签中,name这个属性的值
  4. print(soup.p['name'])#另一种写法,比较直接

获取标签内容


 
  1. print(soup.p.string)

标签嵌套选择


 
  1. from bs4 import BeautifulSoup
  2. soup = BeautifulSoup(html, 'lxml')#传入解析器:lxml
  3. print(soup.head.title.string)

子节点和子孙节点


 
  1. html = """
  2. <html>
  3. <head>
  4. <title>The Dormouse's story</title>
  5. </head>
  6. <body>
  7. <p class="story">
  8. Once upon a time there were three little sisters; and their names were
  9. <a href="http://example.com/elsie" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="sister" id="link1">
  10. <span>Elsie</span>
  11. </a>
  12. <a href="http://example.com/lacie" rel="external nofollow" rel="external nofollow"rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow"class="sister" id="link2">Lacie</a>
  13. and
  14. <a href="http://example.com/tillie" rel="external nofollow" rel="external nofollow"rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow"rel="external nofollow" class="sister" id="link3">Tillie</a>
  15. and they lived at the bottom of a well.
  16. </p>
  17. <p class="story">...</p>
  18. """
  19.  
  20.  
  21. from bs4 import BeautifulSoup
  22. soup = BeautifulSoup(html, 'lxml')#传入解析器:lxml
  23. print(soup.p.contents)#获取指定标签的子节点,类型是list

另一个方法,child:


 
  1. from bs4 import BeautifulSoup
  2. soup = BeautifulSoup(html, 'lxml')#传入解析器:lxml
  3. print(soup.p.children)#获取指定标签的子节点的迭代器对象
  4. for i,children in enumerate(soup.p.children):#i接受索引,children接受内容
  5. print(i,children)

输出结果与上面的一样,多了一个索引。注意,只能用循环来迭代出子节点的信息。因为直接返回的只是一个迭代器对象。

获取子孙节点:


 
  1. from bs4 import BeautifulSoup
  2. soup = BeautifulSoup(html, 'lxml')#传入解析器:lxml
  3. print(soup.p.descendants)#获取指定标签的子孙节点的迭代器对象
  4. for i,child in enumerate(soup.p.descendants):#i接受索引,child接受内容
  5. print(i,child)

父节点和祖先节点

parent


 
  1. from bs4 import BeautifulSoup
  2. soup = BeautifulSoup(html, 'lxml')#传入解析器:lxml
  3. print(soup.a.parent)#获取指定标签的父节点

parents


 
  1. from bs4 import BeautifulSoup
  2. soup = BeautifulSoup(html, 'lxml')#传入解析器:lxml
  3. print(list(enumerate(soup.a.parents)))#获取指定标签的祖先节点

兄弟节点


 
  1. from bs4 import BeautifulSoup
  2. soup = BeautifulSoup(html, 'lxml')#传入解析器:lxml
  3. print(list(enumerate(soup.a.next_siblings)))#获取指定标签的后面的兄弟节点
  4. print(list(enumerate(soup.a.previous_siblings)))#获取指定标签的前面的兄弟节点

标准选择器

find_all( name , attrs , recursive , text , **kwargs )

可根据标签名、属性、内容查找文档。

name


 
  1. html='''
  2. <div class="panel">
  3. <div class="panel-heading">
  4. <h4>Hello</h4>
  5. </div>
  6. <div class="panel-body">
  7. <ul class="list" id="list-1">
  8. <li class="element">Foo</li>
  9. <li class="element">Bar</li>
  10. <li class="element">Jay</li>
  11. </ul>
  12. <ul class="list list-small" id="list-2">
  13. <li class="element">Foo</li>
  14. <li class="element">Bar</li>
  15. </ul>
  16. </div>
  17. </div>
  18. '''
  19. from bs4 import BeautifulSoup
  20. soup = BeautifulSoup(html, 'lxml')
  21. print(soup.find_all('ul'))#查找所有ul标签下的内容
  22. print(type(soup.find_all('ul')[0]))#查看其类型

下面的例子就是查找所有ul标签下的li标签:


 
  1. from bs4 import BeautifulSoup
  2. soup = BeautifulSoup(html, 'lxml')
  3. for ul in soup.find_all('ul'):
  4. print(ul.find_all('li'))

attrs(属性)

通过属性进行元素的查找


 
  1. html='''
  2. <div class="panel">
  3. <div class="panel-heading">
  4. <h4>Hello</h4>
  5. </div>
  6. <div class="panel-body">
  7. <ul class="list" id="list-1" name="elements">
  8. <li class="element">Foo</li>
  9. <li class="element">Bar</li>
  10. <li class="element">Jay</li>
  11. </ul>
  12. <ul class="list list-small" id="list-2">
  13. <li class="element">Foo</li>
  14. <li class="element">Bar</li>
  15. </ul>
  16. </div>
  17. </div>
  18. '''
  19.  
  20.  
  21. from bs4 import BeautifulSoup
  22. soup = BeautifulSoup(html, 'lxml')
  23. print(soup.find_all(attrs={'id': 'list-1'}))#传入的是一个字典类型,也就是想要查找的属性
  24. print(soup.find_all(attrs={'name': 'elements'}))

查找到的是同样的内容,因为这两个属性是在同一个标签里面的。

特殊类型的参数查找:


 
  1. from bs4 import BeautifulSoup
  2. soup = BeautifulSoup(html, 'lxml')
  3. print(soup.find_all(id='list-1'))#id是个特殊的属性,可以直接使用
  4. print(soup.find_all(class_='element')) #class是关键字所以要用class_

text

根据文本内容来进行选择:


 
  1. html='''
  2. <div class="panel">
  3. <div class="panel-heading">
  4. <h4>Hello</h4>
  5. </div>
  6. <div class="panel-body">
  7. <ul class="list" id="list-1">
  8. <li class="element">Foo</li>
  9. <li class="element">Bar</li>
  10. <li class="element">Jay</li>
  11. </ul>
  12. <ul class="list list-small" id="list-2">
  13. <li class="element">Foo</li>
  14. <li class="element">Bar</li>
  15. </ul>
  16. </div>
  17. </div>
  18. '''
  19. from bs4 import BeautifulSoup
  20. soup = BeautifulSoup(html, 'lxml')
  21. print(soup.find_all(text='Foo'))#查找文本为Foo的内容,但是返回的不是标签

所以说这个text在做内容匹配的时候比较方便,但是在做内容查找的时候并不是太方便。

方法

find

find用法和findall一模一样,但是返回的是找到的第一个符合条件的内容输出。

ind_parents(), find_parent()

find_parents()返回所有祖先节点,find_parent()返回直接父节点。

find_next_siblings() ,find_next_sibling()

find_next_siblings()返回后面的所有兄弟节点,find_next_sibling()返回后面的第一个兄弟节点

find_previous_siblings(),find_previous_sibling()

find_previous_siblings()返回前面所有兄弟节点,find_previous_sibling()返回前面第一个兄弟节点

find_all_next(),find_next()

find_all_next()返回节点后所有符合条件的节点,find_next()返回后面第一个符合条件的节点

find_all_previous(),find_previous()

find_all_previous()返回节点前所有符合条件的节点,find_previous()返回前面第一个符合条件的节点

CSS选择器 通过select()直接传入CSS选择器即可完成选择


 
  1. html='''
  2. <div class="panel">
  3. <div class="panel-heading">
  4. <h4>Hello</h4>
  5. </div>
  6. <div class="panel-body">
  7. <ul class="list" id="list-1">
  8. <li class="element">Foo</li>
  9. <li class="element">Bar</li>
  10. <li class="element">Jay</li>
  11. </ul>
  12. <ul class="list list-small" id="list-2">
  13. <li class="element">Foo</li>
  14. <li class="element">Bar</li>
  15. </ul>
  16. </div>
  17. </div>
  18. '''
  19. from bs4 import BeautifulSoup
  20. soup = BeautifulSoup(html, 'lxml')
  21. print(soup.select('.panel .panel-heading'))#.代表class,中间需要空格来分隔
  22. print(soup.select('ul li')) #选择ul标签下面的li标签
  23. print(soup.select('#list-2 .element')) #'#'代表id。这句的意思是查找id为"list-2"的标签下的,class=element的元素
  24. print(type(soup.select('ul')[0]))#打印节点类型

再看看层层嵌套的选择:


 
  1. from bs4 import BeautifulSoup
  2. soup = BeautifulSoup(html, 'lxml')
  3. for ul in soup.select('ul'):
  4. print(ul.select('li'))

获取属性


 
  1. from bs4 import BeautifulSoup
  2. soup = BeautifulSoup(html, 'lxml')
  3. for ul in soup.select('ul'):
  4. print(ul['id'])# 用[ ]即可获取属性
  5. print(ul.attrs['id'])#另一种写法

获取内容


 
  1. from bs4 import BeautifulSoup
  2. soup = BeautifulSoup(html, 'lxml')
  3. for li in soup.select('li'):
  4. print(li.get_text())

用get_text()方法就能获取内容了。

总结

推荐使用lxml解析库,必要时使用html.parser

标签选择筛选功能弱但是速度快 建议使用find()、find_all() 查询匹配单个结果或者多个结果

如果对CSS选择器熟悉建议使用select()

记住常用的获取属性和文本值的方法

更多关于Python爬虫库BeautifulSoup的介绍与简单使用实例请点击下面的相关链接

分享到:

相关信息

系统教程栏目

栏目热门教程

人气教程排行

站长推荐

热门系统下载