Python3爬虫编程学习笔记(六)BeautifulSoup库入门学习


 

  • 如果觉得XPath语法掌握起来有难度,那么BeautifulSoup库就可以象学习Python基础知识一样简单,它是直接从获取的网页源代码中读取字符串。由于它是将整个文档树一次性解析并读入内存,速度稍慢、资源占用稍高一点,胜在简单实用。

详细请参阅中文文档:https://www.crummy.com/software/BeautifulSoup/bs4/doc/index.zh.html

一、BeautifulSoup库安装

BeautifulSoup是第三方库,需要安装才能导入使用:

pip install beautifulsoup4 -i https://pypi.douban.com/simple/

如果没有安装“lxml‘库,还需要安装,以配合解析网页用,该当同上。

二、创建soup对象

要使用BeautifulSoup,必须先创建Soup对象:

1. 导入模块


from bs4 import BeautifulSoup

2. 创建对象

# 使用'lxml'解析器,速度较快,也可以使用标准库解析器'parser.HTML'或其他解析器
soup = BeautifulSoup(html, 'lxml')

三、BeautifulSoup提取数据

1.获取标签的属性

  • 通过形如字典键值(下标)的形式:
href = a['href']    # 推荐使用这种形式
href = a.attrs['href']  # 通过attrs属性形式

2.获取标签的文本

  • .string、.strings、.stripped_strings及get_text()方法:
    a. .string:获取某个标签下的非标签字符串(含与标签同一行的注释文本,多行用.contents),返回一个字符串。
    b. .strings:获取某个标签下的所有子孙标签字符串,返回一个生成器。
    c. .stripped_strings:获取某个标签下的所有子孙标签字符串,返回一个生成器,并会去掉所有空白字符。
    d. get_text():获取某个标签下的子孙非标签字符串,返回一个字符串,不方便数据清洗。
    e. .contents:获取不同行的注释文本
    strs = p.contents

### 3.find_all()的用法

在提取标签数据的时候,第一个是标签的名字。如果在提取标签时想使用标签的属性进行过滤,可以在方法中通过关键字参数过滤,将属性的名字及对应的值传递"class=‘XXX’",或者是使用"attrs"属性,将所有的属性以及对应的值话一个字典中传给"attrs"属性?

trs = soup.find_all('tr')   # 获取所有的tr标签
for tr in trs:
    tr.find_all('td',class_='list-item')    # 使用参数形式,class后加下划线
    tr.find_all('td',attrs={'class':'list-item'})
    # 使用attrs属性形式,如果是name属性,建议用此形式查找
  • 有时候在提取标签时,不想提取那么多,可以使用’limit’参数进行限定查找次数:
trs=soup.find_all('tr', limit=2)[1]  # 只获取前2个tr标签,减少资源占用,加快查找速度
  • find()与find_all()的区别:
    1)find():找到第一个符合条件的标签就结束并返回目标值,返回一个元素
    2)find_all():将所有满足条件的标签都以列表的形式返回,参数limit=1达到与find()一样效果。

4.提取数据练习

以百度首页源码为例,从第3个div开始,提取div下a节点的所有文本,代码如下:

# -*- encoding: utf-8 -*-
from bs4 import BeautifulSoup

html = '''
<!DOCTYPE html>
<html>
<head>
    <meta content="text/html;charset=utf-8" http-equiv="content-type" />
    <meta content="IE=Edge" http-equiv="X-UA-Compatible" />
    <meta content="always" name="referrer" />
    <link href="https://ss1.bdstatic.com/5eN1bjq8AAUYm2zgoY3K/r/www/cache/bdorz/baidu.min.css" rel="stylesheet" type="text/css" />
    <title>百度一下,你就知道 </title>
</head>
<body link="#0000cc">
  <div id="wrapper">
    <div id="head">
        <div class="head_wrapper">
          <div id="u1">
            <a class="mnav" href="http://news.baidu.com" name="tj_trnews">新闻 </a>
            <a class="mnav" href="https://www.hao123.com" name="tj_trhao123">hao123 </a>
            <a class="mnav" href="http://map.baidu.com" name="tj_trmap">地图 </a>
            <a class="mnav" href="http://v.baidu.com" name="tj_trvideo">视频 </a>
            <a class="mnav" href="http://tieba.baidu.com" name="tj_trtieba">贴吧 </a>
            <a class="bri" href="http://www.baidu.com/more/" name="tj_briicon" style="display: block;">更多产品 </a>
            <tb>测试</tb>
            <tb>Tne end</tb>
          </div>
        </div>
    </div>
        <p><!--我是注释字符串--></p>
  </div>
</body>
< / html > '''

bs = BeautifulSoup(html, 'lxml')  # 可以使用其他解析器
divs = bs.find_all('div')[3:]   # 第3个div起到最后止才有需要的数据
# print(divs)
for div in divs:   # 遍历div节点,提取有用数据
    info = {}
    # print(div.get_text())   # 不方便清洗数据
    # infos = div.find_all('a') # 在div下查找到需要的节点,并从其列表提取数据
    # news = infos[0].string
    # h123 = infos[1].string
    # map_ = infos[2].string
    # movies = infos[3].string
    # tieba = infos[4].string
    # print(maps)
    # infos = list(div.strings)  # 提取所有非标签的字符串,有空行
    infos=list(div.stripped_strings)    # 提取所有非标签的字符串并支队空白符
    # 将数据存入字典
    info['news'] = news
    info['h123'] = h123
    info['map'] = map_
    info['movies'] = movies
    info['tieba'] = tieba
    # {'news': '新闻', 'hao': 'hao123', 'map': '地图', 'movie': '视频', 'tieba': '贴吧'}
    print(info)

四、CSS选择器

BeautifulSoup中使用CSS选择器,须使用select()方法
具体用法如下:

  1. 根据标签的名字选择:
soup.select('p')
  1. 根据类名选择,要在类的前面加一个点".":
soup.select('.box')  
  1. 根据id名字选择,要在id的前面加一个#号:
soup.select('#box') # 在CSS中,"#"号代表id(一个规范的网页中,id只能出现一次相同的值,如身份证号)  
  1. 组合查找:
    4.1 查找子孙元素,要在子孙元素中间有一个空格:
soup.select('.box p')    # 此处"#"号表示后面跟的是类的值  

   4.2 查找直接子元素,要在直接子元素前加一个">"号:

soup.select('.box > p')   # 此处"."号表示后面跟的是类的值  
  1. 根据属性的名字进行查找,应该先写标签名字,然后再在中括号中写属性的值:
soup.select('p[name="username"]')  
  1. 在根据类名或者id进行查找时,如果要根据标签名进行过滤,那么可以在类的前面或id前面加上标签名字:
soup.select('div.line1')
soup.select('div[class="line1"]')
soup.select('div#')  

代码示例:

html = '''<!DOCTYPE html>上例的文本'''
bs = BeautifulSoup(html, 'lxml')

# 1.获取所有的div标签
divs = bs.select('div')
for div in divs:
    print(div)

# 2.获取第2个div标签
div = bs.select('div')[2]
print(div)

# 3.获取所有class = "head_wrapper"的div标签,属性有两种写法
# divs = bs.select('div.head_wrapper')
divs = bs.select('div[class="head_wrapper"]')
for div in divs:
    print(div)

# 4.将所有a标签的"href"值提取出来
a_list = list(bs.select('a'))  # 转换成一个列表,便于提取数据
for a in a_list:
    href = a['href']
    print(href)

# 5.获取所有a标签的文本
divs = bs.select('#u1')
for div in divs:
    infos = list(div.stripped_strings)
    # 转换成一个列表,便于提取数据,如是.strings则不去除空白符
    print(infos)

五、BeautifulSoup库的四种类对象

1、Tag对象

BeautifulSoup中所有的标签都是Tag类型,并且BeautifulSoup本质上也是一个Tag类型,所以一些方法如find/find_all并不是BeautifulSoup的,而是Tag的。

__init__(self, parser=None, builder=None, name=None, namespace=None,
                 prefix=None, attrs=None, parent=None, previous=None,
                 is_xml=None, sourceline=None, sourcepos=None,
                 can_be_empty_element=None, cdata_list_attributes=None,
                 preserve_whitespace_tags=None
    )

如:

from bs4 import BeautifulSoup

bs = BeautifulSoup(html, 'lxml')
print(type(bs))     # <class 'bs4.BeautifulSoup'>

2、NavigableString对象

继承自Python中的str,用起来就跟使用python的str一样,如.string。

from bs4 import BeautifulSoup

bs = BeautifulSoup(html, 'lxml')
a = bs.find('a')
print(a.string) # "新闻",本质上是一个字符串
print(type(a.string))   # <class 'bs4.element.NavigableString'>

3、BeautifulSoup对象

继承自Tag,用来生成BeautifulSoup树,所有方法同Tag,find()/select()等方法都一样能用,在select()查找出来的子节点中也一样能用所有方法。

from bs4 import BeautifulSoup

bs = BeautifulSoup(html, 'lxml')
divs = bs.find_all('div')
for div in divs:
    print(type(div))    # <class 'bs4.element.Tag'>
    break

4、Comment对象

就是继承自NavigableSting,如果在一行可以用.string提取注释的文本,如果存在多行注释,换行了,通过.contents获取。

from bs4 import BeautifulSoup

bs = BeautifulSoup(html, 'lxml')
p = bs.find('p')
# print(p.string)     # 换行了,返回None
# 如果注释不在同一行就用ceontents遍历
print(p.contents)   # 返回包括换行符的列表
# print(type(p.string))   # <class 'bs4.element.Comment'>
print(type(p.contents))   # <class 'list'>

六、遍历文档树

  • 使用contents和children遍历soup文档树。

返回某个标签下的直接子元素,其中也包括字符串,区别:conntents返回列表,children返回迭代器(迭代器对象)。

1.contents

from bs4 import BeautifulSoup

bs = BeautifulSoup(html, 'lxml')
p = bs.find('p')
# 如果注释不在同一行就用ceontents遍历
print(p.contents)   # 返回包括换行符的列表['\n', '我是注释字符串', '\n']
print(type(p.contents))   # <class 'list'>
for element in p.contents:
    print(element)

2.children

from bs4 import BeautifulSoup

bs = BeautifulSoup(html, 'lxml')
print(type(bs.head.children))  # <class 'list_iterator'>
for h in bs.head.children:
    print(h)

 


说明:本学习笔记根据晚上观看学习B站乐林贝斯发布的视频《Python爬虫】新手强烈推荐:Python爬虫教程,学爬虫这一套就够了》所作笔记,非常感谢老师!


学习笔记系列:

Python3爬虫编程学习笔记(一)缘由

Python3爬虫编程学习笔记(二)爬虫原理

Python3爬虫编程学习笔记(三)学习urllib库基本用法

Python3爬虫编程学习笔记(四)学习Requests第三方库基本用法

Python3爬虫编程学习笔记(五)实战:爬取安居客房屋信息之 XPath学习

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值