Python学习 Day43 数据解析-BeautifulSoup 07

BeautifulSoup 解析数据

一、BeautifulSoup概述

1.BeautifulSoup

  • 是一个可以从HTML或XML文档中提取数据的Python库
  • 功能简单强大、容错能力高、文档相对完善,清晰易懂
  • 非Python标准模块,需要安装才能使用

2.安装方式

  • pip install bs4 -i http://pypi.douban.com/simple --trusted-host pypi.douban.com

3.测试方式

  • import bs4

4.解析器

BeautifulSoup支持Python标准库中的HTML解析器,还支持一些第三方的解析器,如果不安装第三方解析器,则Python会使用默认解析器

(1)标准库

  • 使用方法:BeautifulSoup(html,‘html.parser’)
  • 优点:内置标准库,速度适中,文档容错能力强
  • 缺点:Python3.2版本前的文档容错能力差

(2)lxml HTML

  • 使用方法:BeautifulSoup(html,‘lxml’)
  • 优点:速度快,文档容错能力强
  • 缺点:安装C语言库

(3)lxml XML

  • 使用方法:BeautifulSoup(html,‘xml’)
  • 优点:速度快,唯一支持XML
  • 缺点:安装C语言库

(4)html5lib

  • 使用方法:BeautifulSoup(html,‘html5lib’)
  • 优点:容错能力最强,可生成HTML5
  • 缺点:运行慢,扩展差

二、代码创建bs4对象

from bs4 import BeautifulSoup

#待解析的文档
html = '''
          <html>
                <head>
                        <title>水面清圆</title>
                </head>
                <body>
                        <h1 class = 'cur book' float = 'left'>一一风荷举</h1>
                        <a href = 'http://www.baidu.com'></a>
                        <h2><!--这里是注释--></h2>
                </body>
          </html>
'''

#选择一个解析器,创建bs对象
bs = BeautifulSoup(html,'lxml')
#获取标签
print(bs.title)
#获取h1标签的所有属性 列表形式存放多个属性值
print(bs.h1.attrs)
#获取单个属性
print(bs.h1.get('class')) #写法1
print(bs.h1['class'])     #写法2
#获取属性值
print(bs.a['href'])
#获取文本
print(bs.title.text)
print(bs.title.string)

#获取内容
print('text:',bs.h2.text)  #仅获取文本内容
print('string:',bs.h2.string)  #获取到h2标签中的所有内容
<title>水面清圆</title>
{
    
    'class': ['cur', 'book'], 'float': 'left'}
['cur', 'book']
['cur', 'book']
http://www.baidu.com
水面清圆
水面清圆
text: 
string: 这里是注释

Process finished with exit code 0

三、BS提取数据常用方法

(一)find()方法

  • 1.返回值类型:Tag
  • 2.功能:提取满足要求的首个数据
  • 3.语法:bs.find(标签,属性)
  • 4.举例:bs.find(‘div’,class_=‘books’)

(二)find_all()方法

  • 1.返回值类型:Tag
  • 2.功能:提取满足要求的所有数据
  • 3.语法:bs.find_all(标签,属性)
  • 4.举例:bs.find_all(‘div’,class_=‘books’)

(三)CSS选择器

  • 1.通过ID查找:bs.select(’#abc’)
  • 2.通过classa查找:bs.select(’.abc’)
  • 3.通过属性查找:bs.select(a[‘class=“abc”’])

(四)Tag对象

  • 1.获取标签:bs.title
  • 2.获取所有属性:bs.title.attrs
  • 3.获取单个属性的值:
    写法1: bs.div.get(‘class’)
    写法2: bs.div.[‘class’]
    写法3: bs.a(‘href’)

代码实现

from bs4 import  BeautifulSoup
#待解析的文档
html = '''

              <title>晴空一鹤排云上</title>
                  <div class = 'info' float = 'left'>便引诗情到碧霄</div>
                  <div class = 'info' float = 'right' id = 'gb'>
                       <span>好好学习,天天向上</span>
                       <a href = 'http://www.baidu.com'></a>
                  </div>
                  <span>我是第二个span</span>
              
'''
#解析数据
bs = BeautifulSoup(html,'lxml')
#获得Tag对象
print(bs.title,type(bs.title))

print('\n--------------bs.find()方法------------------------')
#bs.find()方法:获取满足条件的第一个标签,其类型也为Tag
print(bs.find('div',class_='info'),type(bs.find('div',class_='info')))

print('\n--------------bs.find_all()方法------------------------')
#bs.find_all()方法:获取满足条件的所有标签,返回的是一个标签列表
print(bs.find_all('div',class_='info'),type(bs.find_all('div',class_='info')))

print('\n-----------------------遍历每一个标签---------------------')
for item in bs.find_all('div',class_ = 'info'):
    print(item,type(item))

print('\n--------------获取属性--------------------')
print(bs.find_all('div',attrs={
    
    'float':'right'}))

print('\n---------------CSS选择器---------------------')
print(bs.select('#gb'))
print('\n------------------------------------------------')
print(bs.select('.info'))

print('\n--------------获取div标签下的span标签--------------------------')
print(bs.select('div>span'))

print('\n------------------------------------------------')
print(bs.select('div.info>span'))

print('\n------------------获取标签中的文本内容------------')
for item in bs.select('div.info>span'):
    print(item.text)
<title>晴空一鹤排云上</title> <class 'bs4.element.Tag'>

--------------bs.find()方法------------------------
<div class="info" float="left">便引诗情到碧霄</div> <class 'bs4.element.Tag'>

--------------bs.find_all()方法------------------------
[<div class="info" float="left">便引诗情到碧霄</div>, <div class="info" float="right" id="gb">
<span>好好学习,天天向上</span>
<a href="http://www.baidu.com"></a>
</div>] <class 'bs4.element.ResultSet'>

-----------------------遍历每一个标签---------------------
<div class="info" float="left">便引诗情到碧霄</div> <class 'bs4.element.Tag'>
<div class="info" float="right" id="gb">
<span>好好学习,天天向上</span>
<a href="http://www.baidu.com"></a>
</div> <class 'bs4.element.Tag'>

--------------获取属性--------------------
[<div class="info" float="right" id="gb">
<span>好好学习,天天向上</span>
<a href="http://www.baidu.com"></a>
</div>]

---------------CSS选择器---------------------
[<div class="info" float="right" id="gb">
<span>好好学习,天天向上</span>
<a href="http://www.baidu.com"></a>
</div>]

------------------------------------------------
[<div class="info" float="left">便引诗情到碧霄</div>, <div class="info" float="right" id="gb">
<span>好好学习,天天向上</span>
<a href="http://www.baidu.com"></a>
</div>]

--------------获取div标签下的span标签--------------------------
[<span>好好学习,天天向上</span>]

------------------------------------------------
[<span>好好学习,天天向上</span>]

------------------获取标签中的文本内容------------
好好学习,天天向上

Process finished with exit code 0


四、案例

爬取淘宝网首页

import requests
from bs4 import BeautifulSoup

#请求的URL:淘宝网首页
url = 'https://uland.taobao.com/'
#加入请求头
headers = {
    
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36'}
#发送请求
resp = requests.get(url,headers)
#返回一个HTML文档

#创建一个bs对象,解析返回的HTML文档
bs = BeautifulSoup(resp.text,'lxml')
#查询所有的a标签
a_list = bs.find_all('a')
#遍历每个a标签,以获取其href的属性值
for a in a_list:
    url = a.get('href')
    #print(url)
    if url == None:    #去掉href为空值的标签属性
        continue
    if url.startswith('http') or url.startswith('https'):  #获取以HTTP或HTTPS开头的完整网址
        print(url)

输出结果为可以跳转的链接

https://s.click.taobao.com/t?union_lens=lensId%3AOPT%401601203401%400b0f99df_a5b3_174cf28f3bb_ad79%4001%3BeventPageId%3A20150318020000648&e=m%3D2%26s%3Diaj%2F%2FMChDMNw4vFB6t2Z2iperVdZeJviePMclkcdtjxyINtkUhsv0K5mYvcBEhv8U9RX0Iw%2BkeJD415GGSsrJ4YxhNUZ2i3GTlT4SLzYDiBT2M421%2BABgTvflh4%2Fhqj89CGjsatFbg%2FkxFiXT%2FI5kdHG0mETTJw4I%2FQKsMyWv9lyeNAoQluSar7Bu%2FpJjtAXjXL88Z9Mt2nGDmntuH4VtA%3D%3D&pid=mm_0_0_0
https://s.click.taobao.com/t?union_lens=lensId%3AOPT%401602583439%400b5dc12f_df39_175216aa7d3_3ba4%4001%3BeventPageId%3A20150318020000813&e=m%3D2%26s%3DVSDHOXPRC4YcQipKwQzePCperVdZeJviePMclkcdtjxyINtkUhsv0LByEUqSWs8wxHXUNZRa3F5D415GGSsrJ4YxhNUZ2i3GTlT4SLzYDiBT2M421%2BABgTvflh4%2Fhqj89CGjsatFbg%2FkxFiXT%2FI5kdv2ej9RFznDujXyQ8P5hEAW95D0t3aOisosmJjNa%2FrGYpyF7ku%2BxKjfv8uao0UzJSWcMOnOtXCYRnn6ynij93lsDvbh8Qt7h%2F7mglw2LhJ8IdKpkygapz%2FOumdbRSBMWogPh2VpbvcT8PwOkD4ulZfxvNaaibhIncDlE6H93yEw17wnkme1OdGDcT9IgYeWFwpobexl%2Fx%2FZ&pid=mm_0_0_0
https://s.click.taobao.com/t?union_lens=lensId%3AOPT%401600161414%400b59e276_31e8_174910d7ee5_1434%4001%3BeventPageId%3A20150318020000406&e=m%3D2%26s%3D5LNEiCktsG5w4vFB6t2Z2iperVdZeJviePMclkcdtjxyINtkUhsv0KBG0TwCFKWFemLun%2Boqc%2FVD415GGSsrJ4YxhNUZ2i3GTlT4SLzYDiBT2M421%2BABgTvflh4%2Fhqj89CGjsatFbg%2FkxFiXT%2FI5kdv2ej9RFznDujXyQ8P5hEAW95D0t3aOisosmJjNa%2FrGraOxjvWhHnYV5fRYrrSW6WwO9uHxC3uHfE%2BH0gbC0KpkDV443qLdLqxZ2nVWPAAw2n9Az55wlDRExsN3p515W%2FKamps88B8EQWLobdpSETDGDF1NzTQoPw%3D%3D&&pid=mm_0_0_0
https://s.click.taobao.com/t?union_lens=lensId%3AOPT%401602583439%400b1a25d9_3fc2_175216aa7eb_ac58%4001%3BeventPageId%3A20150318020000814&e=m%3D2%26s%3D3q2KSPwGXwYcQipKwQzePCperVdZeJviePMclkcdtjxyINtkUhsv0LByEUqSWs8wxHXUNZRa3F5D415GGSsrJ4YxhNUZ2i3GTlT4SLzYDiBT2M421%2BABgTvflh4%2Fhqj89CGjsatFbg%2FkxFiXT%2FI5kdv2ej9RFznDujXyQ8P5hEAW95D0t3aOisosmJjNa%2FrGYpyF7ku%2BxKjfv8uao0UzJSWcMOnOtXCYRnn6ynij93lsDvbh8Qt7h%2F7mglw2LhJ8IdKpkygapz8i98XAIvg9KYgPh2VpbvcT8PwOkD4ulZfxvNaaibhIncDlE6H93yEw17wnkme1OdGDcT9IgYeWFwpobexl%2Fx%2FZ&pid=mm_0_0_0
https://www.etao.com/cjfl/info.htm?activityId=1495387
https://s.click.taobao.com/t?e=m%3D2%26s%3DaCBbXzf6%2Bp8cQipKwQzePDAVflQIoZepK7Vc7tFgwiFRAdhuF14FMTCw9kUE1PCMaqAeRGk4m9Lb6q32bH9H5L2YnZ7gs%2Faz&pid=mm_0_0_0
https://mo.m.taobao.com/union/live?pid=mm_0_0_0

Process finished with exit code 0

在这里插入图片描述

Guess you like

Origin blog.csdn.net/ShengXIABai/article/details/115701962
Recommended