Beautiful Soup的学习笔记

参考文档:Beautiful Soup 官方中文文档

本文大多数内容来自官方文档,在这里只是做一下学习总结,方便日后查询和补充深入学习。

Beautiful Soup基本用法

简介

  • Beautiful Soup是一个Python的HTML或XML的解析库,可以使用它来从网页中解析数据
  • Beautiful Soup自动将输入文档转换为Unicode编码,输出文档转换为UTF-8编码

安装Beautiful Soup以及安装解析器

# 安装Beautiful Soup
pip install beautifulsoup4
# 或者
easy_install beautifulsoup4

# 安装解析器
pip install lxml
pip install html5lib
# 推荐使用lxml作为解析器,因为效率更高.
解析器使用方法优势劣势
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”)

BeautifulSoup(markup, [“lxml-xml”])
速度快
唯一支持XML的解析器
需要安装C语言库
html5libBeautifulSoup(markup, “html5lib”)最好的容错性
以浏览器的方式解析文档
生成HTML5格式的文档
速度慢
不依赖外部扩展

基本用法

3.1 使用Beautiful Soup

将一段文档传入BeautifulSoup 的构造方法,就能得到一个文档的对象, 可以传入一段字符串或一个文件句柄.

文档被转换成Unicode,并且HTML的实例都被转换成Unicode编码.

###demo1.py
from bs4 import BeautifulSoup
soup = BeautifulSoup('<p>Hello</p>', 'lxml') 
# soup = BeautifulSoup(open("index.html"))
print(soup.p.string)

##
Hello

3.2 编码问题

3.2.1 输入编码

任何HTML或XML文档都有自己的编码方式,但是使用Beautiful Soup解析后,文档都被转换成了Unicode。BeautifulSoup 对象的 .original_encoding 属性记录了自动识别编码的结果,如果预先知道文档编码,就可以在创建Beautiful Soup对象时通过from_coding参数来设置,减少自动检查编码错误的几率。如果不知道文档编码,在试错的同时,可以通过exclude_encodings参数将错误编码排除,从而增加自动检测正确的几率。

soup = BeautifulSoup(markup, from_encoding="iso-8859-8")
soup = BeautifulSoup(markup, exclude_encodings=["ISO-8859-7"])
3.2.2 输出编码

通过Beautiful Soup输出文档时,不管输入文档是什么编码方式,输出编码均为UTF-8编码。
如果不想用UTF-8编码输出,可以将编码传入prettify(),或者调用 BeautifulSoup 对象或任意节点的 encode() 方法

print(soup.prettify("latin-1"))
soup.p.encode("latin-1")
##demo2.py
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>
"""
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'lxml')   # Beautifulsoup对象赋给soup
print(soup.prettify())
print(soup.title.string)  # 选中title节点,调用string或者text属性获取文本内容
print(soup.title.text)


# html是一个不完整的字符串,而初始化`Beautifulsoup`的时候,就会自动补全
# prettify()方法是字符串以标准的缩进格式进行输出

# 结果输出:(文档过长,进行删除)

节点选择器

## demo3.py
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>
"""

from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'lxml')

# 节点选择、类型
print(soup.title)
print(type(soup.title))
print(soup.title.string)
print(soup.head)
print(soup.p)

# 提取信息
print(soup.title.name)
print(soup.p.attrs)
print(soup.p.attrs['name'])

# 结果输出
<title>The Dormouse's story</title>
<class 'bs4.element.Tag'>
The Dormouse's story
<head><title>The Dormouse's story</title></head>
<p class="title" name="dromouse"><b>The Dormouse's story</b></p>
title
{'class': ['title'], 'name': 'dromouse'}
dromouse
  • 利用 .号来选择节点,输出的是包含节点字符串的所有内容 例如选择title节点却输出<title>The Dormouse's story</title>
  • 节点类型都是:<class 'bs4.element.Tag'>,意味着可以进行嵌套调用
  • 当有多个节点时,print(soup.p)这种方式只会选择第一个匹配到的节点,其他节点会忽略
  • 提取信息
    • 获取节点名称——name属性
    • 获取所有属性——attrs属性(以字典形式返回),然后使用字典语法提取某一个。
    • 获取内容——string属性
    • 获取内容——如果标签有多个字符串,可以使用.strings来循环获取
    • 获取内容——输出的字符串中可能包含了很多空格或空行,使用.stripped_strings可以去除多余空白内容
html = """
<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>
"""
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'lxml')
print(soup.p.contents)  # 列表
print(soup.p.children)  # 生成器
for i, child in enumerate(soup.p.children):
    print(i, child)
print(soup.a.parent)


#结果输出
[<b>The Dormouse's story</b>]
<list_iterator object at 0x0000024963364630>
0 <b>The Dormouse's story</b>
<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>
    • 关联选择
    • 子节点
      • .contents——返回一个列表,里面的元素都是选择节点的直接子节点,有文本也有节点。但是不会把子孙节点单独选出来
      • .children——这是一个生成器对象,用循环得到的内容跟.contents一样
    • 子孙节点
      • .descendants——这也是一个生成器对象,它会递归查询所有子节点,然后得到所有的子孙节点
    • 父节点
      • .parent——获取某个节点元素的父节点,
      • .parents——(生成器对象)获取所有的祖先节点
    • 兄弟节点
      • .next_sibling——获取节点的下一个节点元素
      • .previous_sibling——获取节点的上一个元素
      • .next_siblings——返回所有后面的兄弟节点的生成器
      • .previous_siblings——返回所有前面的兄弟节点的生成器

方法选择器

find_all()

find_all(name, attrs, recursive, text, **kwargs) 这个方法搜索当前tag的所有tag子节点,并判断是否符合过滤器的条件

html='''
<div class="panel">
    <div class="panel-heading">
        <h4>Hello</h4>
    </div>
    <div class="panel-body">
        <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" name="elements">
            <li class="element">Foo</li>
            <li class="element">Bar</li>
        </ul>
    </div>
</div>
'''
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'lxml')
  • name:可以查找所有名字为name的tag,字符串对象会被自动忽略。返回一个列表类型,每个元素都是<class 'bs4.element.Tag'>,因此可以继续嵌套查询。

    • name的参数值:任一类型的过滤器,字符串,正则表达式,列表,方法或是True

    • # 下面方法校验了当前tag,如果包含 class 属性却不包含 id 属性,那么将返回 True:
      def has_class_but_no_id(tag):
          return tag.has_attr('class') and not tag.has_attr('id')
      
      # 将这个方法作为参数传入 find_all() 方法,将得到所有满足条件的标签:
      soup.find_all(has_class_but_no_id)
      # 可以看到返回结果中,只有满足“含有class属性,不含有id属性”的标签被返回
      
# 根据name
print(soup.find_all(name='ul'))  
print(type(soup.find_all(name='ul')[0]))
for ul in soup.find_all(name='ul'):
    print(ul.find_all(name='li'))
    for li in ul.find_all(name='li'):
        print(li.string)
#
<class 'bs4.element.Tag'>
[<li class="element">Foo</li>, <li class="element">Bar</li>, <li class="element">Jay</li>]
Foo
Bar
Jay
[<li class="element">Foo</li>, <li class="element">Bar</li>]
Foo
Bar
  • keyword参数

    如果一个指定名字的参数不是搜索内置的参数名时,搜索时会把该参数当做指定名字tag的属性来搜索。
    如果包含一个名字为id的数,Beautiful Soup会搜索每个tag的"id"属性

print(soup.find_all(id='list-2'))
[<ul class="list list-small" id="list-2" name="elements">
<li class="element">Foo</li>
<li class="element">Bar</li>
</ul>]

​ 如果传入href参数,Beautiful Soup会搜索每个tag的"href"属性。

soup.find_all(href=re.compile("^https://"))
#搜寻所有 href为https 开头的标签

​ 搜索指定名字的属性可以使用的参数值包括字符串、正则表达式、列表、True

soup.find.all(id=True)
# 搜索查找所有包含id属性的标签,无论id的值是什么

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

soup.find_all(href=re.compile("^https://"),id='link')
# 搜索查找所有id为link href为https开头的标签

​ 注意:有些tag属性不能在搜索中使用,例如html5中的data-*属性

soup = BeautifulSoup('<div data-foo="value">foo!</div>')
soup.find_all(data-foo = "value")
#SyntaxError: keyword can't be an expression
# 通过attrs属性就可以实现
soup.find_all(attrs={'data-foo':'value'})
#[<div data-foo="value">foo!</div>]
  • attrs:传入属性来查询,返回一个列表类型。查询class属性时 要添加下划线,因为class在Python里是一个关键字
    • class_参数同样接受不同类型的过滤器,字符串,正则表达式,方法,或者True
# attrs
print(soup.find_all(attrs={'id': 'list-1'}))
print(soup.find_all(attrs={'name': 'elements'}))
print(soup.find_all(class_='element'))
[<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" name="elements">
<li class="element">Foo</li>
<li class="element">Bar</li>
</ul>]
[<li class="element">Foo</li>, <li class="element">Bar</li>, <li class="element">Jay</li>, <li class="element">Foo</li>, <li class="element">Bar</li>]

​ tag的 class 是多值属性,按照css类名搜索tag的时候,可以分别搜索tag中的每个类名

soup = BeautifulSoup('<p class="body table"></p>')
soup.find_all('p',class_='body')
#['<p class="body table"></p>']

soup.find_all('p',class_='table')
#['<p class="body table"></p>']

​ 同时使用 class_ 也可以进行对css类名的完全匹配

soup.find_all('p',class_='body tabel')
#['<p class="body table"></p>']
#注意:如果在使用完全匹配class值的时候,如果css类名的顺序与实际不符,则不会搜索到正确的结果
  • text: 传入的形式可以是字符串,正则表达式,列表,True
# text
# re.compile('Foo') 是一个正则模式
# 找出包含”Foo”的文本
print(soup.find_all(text=re.compile('Foo')))
# ['Foo', 'Foo']

# 包含"FOO"的li标签 
print(soup.find_all("li", text="Foo"))
  • limit:限制返回结果
soup.find_all('a',limilt=2)
#只返回满足搜索条件的前两个
  • recursive:默认的是搜索当前tag下的所有子孙节点,查找符合我们要求的tag。如果我们只想搜索当前tag的直接子节点,可以使用参数 recursive = False

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

print(soup.find_all(['ul','li']))

# 结果输出
[<ul class="list" id="list-1">
<li class="element">Foo</li>
<li class="element">Bar</li>
<li class="element">Jay</li>
</ul>, <li class="element">Foo</li>, <li class="element">Bar</li>, <li class="element">Jay</li>, <ul class="list list-small" id="list-2" name="elements">
<li class="element">Foo</li>
<li class="element">Bar</li>
</ul>, <li class="element">Foo</li>, <li class="element">Bar</li>]

find()

find()方法返回的是单个元素,但依然是<class 'bs4.element.Tag'>,而find_all()是返回列表

除此之外还有

  • find_parents()find_parent()——前者返回所有祖先节点,后者返回直接父节点
  • find_next_siblings()find_next_sibling()——前者返回后面所有的兄弟节点,后者返回后面第一个兄弟节点
  • find_previous_siblings()find_previous_sibling()
  • find_all_next()——返回节点后所有符合条件的节点
  • find_next()——返回第一个符合条件的节点
  • find_all_previous()find_previous()

css选择器

调用select()方法,传入相应的CSS选择器就行

html='''
<div class="panel">
    <div class="panel-heading">
        <h4>Hello</h4>
    </div>
    <div class="panel-body">
        <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">Foo</li>
            <li class="element">Bar</li>
        </ul>
    </div>
</div>
'''
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'lxml')

# 选择class为panel下的class为panel-heading的节点
print(soup.select('.panel .panel-heading'))

# 选择所有ul节点下的所有li节点
print(soup.select('ul li'))
#for ul in soup.select('ul'):
	#print(ul.select('li'))
    #print(ul['id'])  # 获取属性
    #print(ul.attrs['id']) # 获取属性
#for li in soup.select('li'):
#    print('Get Text:', li.get_text())  # 获取文本
#    print('String:', li.string)	# 获取文本

# 选择id为list-2下class为element
print(soup.select('#list-2 .element'))

# <class 'bs4.element.Tag'> 也支持嵌套选择
print(type(soup.select('ul')[0]))  

[<div class="panel-heading">
<h4>Hello</h4>
</div>]
[<li class="element">Foo</li>, <li class="element">Bar</li>, <li class="element">Jay</li>, <li class="element">Foo</li>, <li class="element">Bar</li>]
[<li class="element">Foo</li>, <li class="element">Bar</li>]
<class 'bs4.element.Tag'>
>>> 

  • 嵌套选择
  • 获取属性:节点['属性名称']节点.attrs['属性名称']
  • 获取文本:get_text(),节点.string

解析部分文档——SoupStrainer

引入

如果仅仅因为想要查找文档中的标签而将整片文档进行解析,实在是浪费内存和时间.最快的方法是从一开始就把标签以外的东西都忽略掉。SoupStrainer 类可以定义文档的某段内容,这样搜索文档时就不必先解析整篇文档。只会解析在 SoupStrainer 中定义过的文档.。创建一个 SoupStrainer 对象并作为 parse_only 参数给 BeautifulSoup 的构造方法即可.

SoupStrainer

SoupStrainer 类接受与典型搜索方法相同的参数:name, attrs, recursive , string , **kwargs

from bs4 import SoupStrainer
only_a_tags = SoupStrainer("a") # 某段包含a标签的内容
only_tags_with_id_link2 = SoupStrainer(id="link2") # 某段包含id属性值为link2,a标签的内容

def is_short_string(string):
    return len(string) < 10
only_short_strings = SoupStrainer(string=is_short_string) # 文本长度小于10的内容

官方文档的验证例子

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

print(BeautifulSoup(html_doc, "html.parser", parse_only=only_a_tags).prettify())
# <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(BeautifulSoup(html_doc, "html.parser", parse_only=only_tags_with_id_link2).prettify())
# <a class="sister" href="http://example.com/lacie" id="link2">
#  Lacie
# </a>

print(BeautifulSoup(html_doc, "html.parser", parse_only=only_short_strings).prettify())
# Elsie
# ,
# Lacie
# and
# Tillie
# ...
#

关于本文章有任何疑问请联系我,欢迎大家的指正和建议。
QQ邮箱:1049951363@qq.com
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值