BeautifulSoup库详解

BeautifulSoup4库

和 lxml 一样,Beautiful Soup 也是一个HTML/XML的解析器,主要的功能也是如何解析和提取 HTML/XML 数据。

安装和文档:

安装:
pip install bs4

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

几大解析工具对比:

在这里插入图片描述

简单使用:

from bs4 import BeautifulSoup

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

soup = BeautifulSoup(html,'lxml')
print(soup.prettify()) #可以不添加.prettify(),但是添加后会让输出更美观。

BeautifulSoup4主要解析器,以及优缺点

在这里插入图片描述

常见的四种对象:

  1. Tag:BeautifulSoup中所有的标签都是Tag类型,并且BeautifulSoup的对象其实本质上也是一个Tag类型。所以其实一些方法比如find、find_all并不是BeautifulSoup的,而是Tag的。
  2. NavigableString:继承自python中的str,用起来就跟使用python的str是一样的。
  3. BeautifulSoup:继承自Tag。用来生成BeaufifulSoup树的。对于一些查找方法,比如find、select这些,其实还是Tag的。
  4. Comment:这个也没什么好说,就是继承自NavigableString。

示例:

#--coding:utf-8--
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>
<b><!--Hey, buddy. Want to buy a used parser?--></b>
"""

from bs4 import BeautifulSoup

# #打印输出的结果会提示警告:UserWarning: No parser was explicitly specified,…………
# soup = BeautifulSoup(html)
# print(soup)

# #指定解析器后,警告消失
# soup = BeautifulSoup(html,'lxml')
# print(soup)

# #对对象Tag的操作(BeautifulSoup中所有的标签都是Tag类型)
# soup = BeautifulSoup(html,'lxml')
# print(soup.p)  #输出标签p,但是只能输出第一个p
# print(soup.p.name)  #输出标签名
# print(soup.p.attrs)  #以字典的形式输出标签p的内容
# print(soup.p['class'])  #获取标签p中class的属性,或者用soup.p.get('class')同样可以获取到

# #修改html中某项的属性
# soup = BeautifulSoup(html,'lxml')
# soup.p['class'] = 'new'
# print(soup.p)

# #打印soup.p(第一个p标签)的内容
# soup = BeautifulSoup(html,'lxml')
# print(soup.p.string)

# #打印b中注释的内容
# soup = BeautifulSoup(html,'lxml')
# print(soup.b.string)

contents和children:

返回某个标签下的直接子元素,其中也包括字符串。他们两的区别是:contents返回来的是一个列表,children返回的是一个迭代器。

string和strings、stripped_strings属性以及get_text方法

  1. string:获取某个标签下的非标签字符串。返回来的是个字符串。如果这个标签下有多行字符,那么就不能获取到了。
  2. strings:获取某个标签下的子孙非标签字符串。返回来的是个生成器。
  3. stripped_strings:获取某个标签下的子孙非标签字符串,会去掉空白字符。返回来的是个生成器。
  4. get_text:获取某个标签下的子孙非标签字符串,以普通字符串形式返回

示例:

#--coding:utf-8--
html = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title" name="dromouse"></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>
<b>
<!--Hey, buddy. Want to buy a used parser?-->
</b>
"""
from bs4 import BeautifulSoup

soup = BeautifulSoup(html,'lxml')


# print(soup.head.contents)  #返回列表
# print(soup.head.children)  #返回迭代器,如若需要输出,需用遍历(如下)
# for i in soup.head.children:
#     print(i)

# print(soup.b.strings)  #返回soup下的子孙非标签字符串,返回的是迭代器
# for string in soup.strings:
#     print(string)  #返回soup下的子孙非标签字符串(会出现很多空行)
#     print(repr(string))  #解决空行的方法(输出\n)

# for string in soup.stripped_strings:  #返回soup下的子孙非标签字符串(会去掉空行)
#     print(string)

find_all的使用:

  1. 在提取标签的时候,第一个参数是标签的名字。然后如果在提取标签的时候想要使用标签属性进行过滤,那么可以在这个方法中通过关键字参数的形式,将属性的名字以及对应的值传进去。或者是使用attrs属性,将所有的属性以及对应的值放在一个字典中传给attrs属性。
  2. 有些时候,在提取标签的时候,不想提取那么多,那么可以使用limit参数。限制提取多少个。

find与find_all的区别:

  1. find:找到第一个满足条件的标签就返回。说白了,就是只会返回一个元素。
  2. find_all:将所有满足条件的标签都返回。说白了,会返回很多标签(以列表的形式)。

使用find和find_all的过滤条件:

  1. 关键字参数:将属性的名字作为关键字参数的名字,以及属性的值作为关键字参数的值进行过滤。
  2. attrs参数:将属性条件放到一个字典中,传给attrs参数。

获取标签的属性:

  1. 通过下标获取:通过标签的下标的方式。

    href = a['href']
    
  2. 通过attrs属性获取:示例代码:

    href = a.attrs['href']
    

示例:

#--coding:utf-8--

from bs4 import BeautifulSoup

html = """
<table class="tablelist" cellpadding="0" cellspacing="0">
    <tbody>
        <tr class="h">
            <td class="l" width="374">职位名称</td>
            <td>职位类别</td>
            <td>人数</td>
            <td>地点</td>
            <td>发布时间</td>
        </tr>
        <tr class="even">
            <td class="l square"><a target="_blank" href="position_detail.php?id=33824&keywords=python&tid=87&lid=2218">22989-金融云区块链高级研发工程师(深圳)</a></td>
            <td>技术类</td>
            <td>1</td>
            <td>深圳</td>
            <td>2017-11-25</td>
        </tr>
        <tr class="odd">
            <td class="l square"><a target="_blank" href="position_detail.php?id=29938&keywords=python&tid=87&lid=2218">22989-金融云高级后台开发</a></td>
            <td>技术类</td>
            <td>2</td>
            <td>深圳</td>
            <td>2017-11-25</td>
        </tr>
        <tr class="even">
            <td class="l square"><a target="_blank" href="position_detail.php?id=31236&keywords=python&tid=87&lid=2218">SNG16-腾讯音乐运营开发工程师(深圳)</a></td>
            <td>技术类</td>
            <td>2</td>
            <td>深圳</td>
            <td>2017-11-25</td>
        </tr>
        <tr class="odd">
            <td class="l square"><a target="_blank" href="position_detail.php?id=31235&keywords=python&tid=87&lid=2218">SNG16-腾讯音乐业务运维工程师(深圳)</a></td>
            <td>技术类</td>
            <td>1</td>
            <td>深圳</td>
            <td>2017-11-25</td>
        </tr>
        <tr class="even">
            <td class="l square"><a target="_blank" href="position_detail.php?id=34531&keywords=python&tid=87&lid=2218">TEG03-高级研发工程师(深圳)</a></td>
            <td>技术类</td>
            <td>1</td>
            <td>深圳</td>
            <td>2017-11-24</td>
        </tr>
        <tr class="odd">
            <td class="l square"><a target="_blank" href="position_detail.php?id=34532&keywords=python&tid=87&lid=2218">TEG03-高级图像算法研发工程师(深圳)</a></td>
            <td>技术类</td>
            <td>1</td>
            <td>深圳</td>
            <td>2017-11-24</td>
        </tr>
        <tr class="even">
            <td class="l square"><a target="_blank" href="position_detail.php?id=31648&keywords=python&tid=87&lid=2218">TEG11-高级AI开发工程师(深圳)</a></td>
            <td>技术类</td>
            <td>4</td>
            <td>深圳</td>
            <td>2017-11-24</td>
        </tr>
        <tr class="odd">
            <td class="l square"><a target="_blank" href="position_detail.php?id=32218&keywords=python&tid=87&lid=2218">15851-后台开发工程师</a></td>
            <td>技术类</td>
            <td>1</td>
            <td>深圳</td>
            <td>2017-11-24</td>
        </tr>
        <tr class="even">
            <td class="l square"><a target="_blank" href="position_detail.php?id=32217&keywords=python&tid=87&lid=2218">15851-后台开发工程师</a></td>
            <td>技术类</td>
            <td>1</td>
            <td>深圳</td>
            <td>2017-11-24</td>
        </tr>
        <tr class="odd">
            <td class="l square"><a id="test" class="test" target='_blank' href="position_detail.php?id=34511&keywords=python&tid=87&lid=2218">SNG11-高级业务运维工程师(深圳)</a></td>
            <td>技术类</td>
            <td>1</td>
            <td>深圳</td>
            <td>2017-11-24</td>
        </tr>
    </tbody>
</table>
"""

soup = BeautifulSoup(html,'lxml')

# 1. 获取所有tr标签
# trs = soup.find_all('tr')
# for tr in trs:
#     print(tr)
#     print('-'*50)
# 2. 获取第2个tr标签
# # for tr in trs:
# #     print(tr)
# #     print('-'*50)
# 3. 获取所有class等于even的tr标签
# trs = soup.find_all('tr',class_ = 'even')
# trs = soup.find_all('tr',attrs={'class':'even'})
# for tr in trs:
#     print(tr)
#     print('-'*50)
# 4. 将所有id等于test,class也等于test的a标签提取出来。
# list = soup.find_all('a',id= 'test',class_='test')
# for a in list:
#     print(a)
# 5. 获取所有a标签的href属性
# alist = soup.find_all('a')
# for a in alist:
#     #1.
#     # href = a['href']
#     # print(href)
#     #2.
#     href = a.attrs['href']
#     print(href)
# 6. 获取所有的职位信息(纯文本)
trs = soup.find_all('tr')[1:]
lists = []
for tr in trs:
    info = {}
    # tds = tr.find_all('td')
    # name = tds[0].string
    # category = tds[1].string
    # info['name']=name
    # info['category']=category
    # infos = list(tr.stripped_strings)
    infos =tr.get_text()
    print(infos)

#     lists.append(info)
# print(list)

CSS选择器:

select方法:

使用以上方法可以方便的找出元素。但有时候使用css选择器的方式可以更加的方便。使用css选择器的语法,应该使用select方法。以下列出几种常用的css选择器方法:

(1)通过标签名查找:
print(soup.select('a'))
(2)通过类名查找:

通过类名,则应该在类的前面加一个.。比如要查找class=sister的标签。示例代码如下:

print(soup.select('.sister'))
(3)通过id查找:

通过id查找,应该在id的名字前面加一个#号。示例代码如下:

print(soup.select("#link1"))
(4)组合查找:

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

print(soup.select("p #link1"))

直接子标签查找,则使用 > 分隔:

print(soup.select("head > title"))
(5)通过属性查找:

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

print(soup.select('a[href="http://example.com/elsie"]'))
(6)获取内容

以上的 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())
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值