Beautifulsoup模块

一、介绍

Beautiful Soup 是一个可以从HTML或XML文件中提取数据的Python库.
它能够通过你喜欢的转换器实现惯用的文档导航,查找,修改文档的方式.
Beautiful Soup会帮你节省数小时甚至数天的工作时间.你可能在寻找
Beautiful Soup3 的文档,Beautiful Soup 3 目前已经停止开发,官网推
荐在现在的项目中使用Beautiful Soup 4, 移植到BS4
#安装 Beautiful Soup
pip install beautifulsoup4

#安装解析器
Beautiful Soup支持Python标准库中的HTML解析器,还支持一些第三方的解析器,其中一个是lxml.
根据操作系统不同,可以选择下列方法来安装lxml: $ apt
-get install Python-lxml $ easy_install lxml $ pip install lxml 另一个可供选择的解析器是纯Python实现的 html5lib , html5lib的解析方式与浏览器相同,可以选择下列方法来安装html5lib: $ apt-get install Python-html5lib $ easy_install html5lib $ pip install html5lib

下表列出了主要的解析器,以及它们的优缺点,官网推荐使用lxml作为解析器,因为效率更高. 在Python2.7.3之前的版本和Python3中3.2.2之前的版本,必须安装lxml或html5lib,

因为那些Python版本的标准库中内置的HTML解析方法不够稳定.

解析器使用方法优势劣势

 

Python标准库

 

BeautifulSoup(markup, "html.parser")

 

  • Python的内置标准库
  • 执行速度适中
  • 文档容错能力强

 

  • Python 2.7.3 or 3.2.2)前 的版本中文档容错能力差

 

lxml HTML 解析器

 

BeautifulSoup(markup, "lxml")

 

  • 速度快
  • 文档容错能力强

 

  • 需要安装C语言库

 

lxml XML 解析器

BeautifulSoup(markup, ["lxml", "xml"])

BeautifulSoup(markup, "xml")

 

  • 速度快
  • 唯一支持XML的解析器

 

  • 需要安装C语言库

 

html5lib

 

BeautifulSoup(markup, "html5lib")

 

  • 最好的容错性
  • 以浏览器的方式解析文档
  • 生成HTML5格式的文档

 

  • 速度慢
  • 不依赖外部扩展

中文文档:https://www.crummy.com/software/BeautifulSoup/bs4/doc/index.zh.html

二、基本使用

html_doc = """
<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>
"""

#基本使用:容错处理,文档的容错能力指的是在html代码不完整的情况下,使用该模块可以识别该错误。
使用BeautifulSoup解析上述代码,能够得到一个 BeautifulSoup 的对象,并能按照标准的缩进格式的结构输出
from bs4 import BeautifulSoup soup=BeautifulSoup(html_doc,'lxml') #具有容错功能 res=soup.prettify() #处理好缩进,结构化显示 print(res)

三、遍历文档树

from bs4 import BeautifulSoup

html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title" id='sss'><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 vvv" 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>
"""
soup=BeautifulSoup(html_doc,'lxml')
# soup=BeautifulSoup(open('a.html',encoding='utf-8'),'lxml')
# print(soup.prettify())
# 遍历文档树:直接通过标签名字选择,特点选择速度快,但只返回第一个

# 1、用法
# print(soup.a,type(soup.a))
# 2、获取标签名称
# print(soup.a.name)
# 3、获取标签的属性
# print(soup.a.attrs)
# 4、获取标签的内容
# print(soup.a.string)
# print(soup.a.strings)
# print(list(soup.strings))
# for line in soup.stripped_strings:
#     print(line)

# 5、嵌套选择
# print(soup.p.b.string)

# 6、子节点、子孙节点
# print(soup.p.contents)
# print(list(soup.p.children))

# 7、父节点 祖先节点
# print(soup.a.parent)
# print(list(soup.a.parents))


# 8、兄弟节点
# print(soup.a.next_sibling)
# print(list(soup.a.next_siblings))
# print(soup.a.previous_sibling)
# print(list(soup.a.previous_siblings))

四、搜索文档树

from bs4 import BeautifulSoup

html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title" id='sss'><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 vvv" 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>
"""
soup=BeautifulSoup(html_doc,'lxml')

# 搜索文档树

# 1、字符过滤器:完全匹配
# name=字符:与标签名完全匹配
# id=字符:与id名完全匹配

# print(soup.find_all('body'))
# print(soup.find_all(name='body'))
# print(soup.find_all(id='link1'))

# 2、正则过滤器
# import re
# print(soup.find_all(name=re.compile('b')))
# print(soup.find_all(class_=re.compile('st')))

# 3、列表过滤器:符合列表中的一个条件即可

# print(soup.find_all(id=['sss','link2']))
# print(soup.find_all(name=['a','p']))


# 4、True
# print(soup.find_all(id=True))
# print(soup.find_all(class_=True))

# for tag in soup.find_all(True):
#     print(tag.name)

# 5、方法过滤器
# tag.has_attr('class')
# tag.has_attr('id')

# def has_class_not_id(tag):
#     return tag.has_attr('class') and not tag.has_attr('id')
#
# print(soup.find_all(has_class_not_id))


# 详细用法:find_all(name,attrs,recursive,text,**kwargs,limit)
import re
# name:
# print(soup.find_all(name='a'))
# print(soup.find_all(name=re.compile('^b')))
# print(soup.find_all(name=['a','b']))
# print(soup.find_all(name=True))

# keyword:key=value
# print(soup.find_all(id='link3'))
# print(soup.find_all(class_='sister',href=re.compile('lacie')))
# print(soup.find_all(class_='sister',href=re.compile('lacie'))[0].name)
# print(soup.find_all(class_='sister',href=re.compile('lacie'))[0].attrs['href'])
# print(soup.find_all(class_='sister',href=re.compile('lacie'))[0].string)

#
# data_soup=BeautifulSoup('<div data-foo="value">foo!</div>','lxml')
# # print(data_soup.find_all(data-foo='value'))    #这样不行
# print(data_soup.find_all(attrs={'data-foo':'value'}))


# class_
# print(soup.find_all(class_='sister vvv'))
# print(soup.find_all(class_='vvv sister'))   #没有匹配上,顺序需一致
# print(soup.find_all(class_='vvv'))
# print(soup.find_all(class_='sister'))


# attrs
# print(soup.find_all(name='a',attrs={'class':'sister'}))


# text
# print(soup.find_all(name='a',text='Tillie'))
# print(soup.find_all(name='b',text=re.compile('y$')))


# limit  限制打印条数
# print(soup.find_all(name='a',limit=2))


# recursive  递归   默认True,为False时不能隔代找

# print(soup.find_all(name='body')[0].find_all(name='a',recursive=False))
# print(soup.find_all(name='body')[0].find_all(name='p',recursive=False))

print(soup.head.title)
print(soup.find('head').find('title'))
find与findall

find_all() 方法将返回文档中符合条件的所有tag,尽管有时候我们只想得到一个结果.
比如文档中只有一个
<body>标签,那么使用 find_all() 方法来查找<body>标签就不
太合适, 使用 find_all 方法并设置 limit=1 参数不如直接使用 find() 方法.
下面两行代码是等价的: soup.find_all(
'title', limit=1) # [<title>The Dormouse's story</title>] soup.find('title') # <title>The Dormouse's story</title> 唯一的区别是 find_all() 方法的返回结果是值包含一个元素的列表,而 find() 方法直接返回结果. find_all() 方法没有找到目标是返回空列表, find() 方法找不到目标时,返回 None . print(soup.find("nosuchtag")) # None soup.head.title 是 tag的名字 方法的简写.这个简写的原理就是多次调用当前tag的 find() 方法: soup.head.title # <title>The Dormouse's story</title> soup.find("head").find("title") # <title>The Dormouse's story</title>

其它方法:见官网:https://www.crummy.com/software/BeautifulSoup/bs4/doc/index.zh.html#find-parents-find-parent

#css选择器
#该模块提供了select方法来支持css,详见官网:https://www.crummy.com/software/BeautifulSoup/bs4/doc/index.zh.html#id37
html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title">
    <b>The Dormouse's story</b>
    Once upon a time there were three little sisters; and their names were
    <a href="http://example.com/elsie" class="sister" id="link1">
        <span>Elsie</span>
    </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>;
    <div class='panel-1'>
        <ul class='list' id='list-1'>
            <li class='element'>Foo</li>
            <li class='element'>Bar</li>
            <li class='element'>Jay</li>
        </ul>
        <ul class='list list-small' id='list-2'>
            <li class='element'><h1 class='yyyy'>Foo</h1></li>
            <li class='element xxx'>Bar</li>
            <li class='element'>Jay</li>
        </ul>
    </div>
    and they lived at the bottom of a well.
</p>
<p class="story">...</p>
"""
from bs4 import BeautifulSoup
soup=BeautifulSoup(html_doc,'lxml')

#1、CSS选择器
print(soup.p.select('.sister'))
print(soup.select('.sister span'))

print(soup.select('#link1'))
print(soup.select('#link1 span'))

print(soup.select('#list-2 .element.xxx'))

print(soup.select('#list-2')[0].select('.element')) #可以一直select,但其实没必要,一条select就可以了

# 2、获取属性
print(soup.select('#list-2 h1')[0].attrs)

# 3、获取内容
print(soup.select('#list-2 h1')[0].get_text())

五、修改文档树

链接:https://www.crummy.com/software/BeautifulSoup/bs4/doc/index.zh.html#id40

 

总结:

#1、推荐使用lxml解析库
#2、讲了三种选择器:标签选择器,find与find_all,css选择器
    1、标签选择器筛选功能弱,但是速度快
    2、建议使用find,find_all查询匹配单个结果或者多个结果
    3、如果对css选择器非常熟悉建议使用select
#3、记住常用的获取属性attrs和文本值get_text()的方法

 

posted @ 2018-01-15 16:55  星雨5213  阅读(92)  评论(0)    收藏  举报