zoukankan      html  css  js  c++  java
  • (三)三种数据解析方式学习

    数据解析三种方式

    1. 正则解析
    2. Xpath解析
    3. BeautifulSoup解析

    一 正则解析

     1 常用正则表达式回顾

     单字符:
            . : 除换行以外所有字符
            [] :[aoe] [a-w] 匹配集合中任意一个字符
            d :数字  [0-9]
            D : 非数字
            w :数字、字母、下划线、中文
            W : 非w
            s :所有的空白字符包,括空格、制表符、换页符等等。等价于 [ f
    
    	v]
            S : 非空白
        数量修饰:
            * : 任意多次  >=0
            + : 至少1次   >=1
            ? : 可有可无  0次或者1次
            {m} :固定m次 hello{3,}
            {m,} :至少m次
            {m,n} :m-n次
        边界:
            $ : 以某某结尾 
            ^ : 以某某开头
        分组:
            (ab)  
        贪婪模式: .*
        非贪婪(惰性)模式: .*?
    
        re.I : 忽略大小写
        re.M :多行匹配
        re.S :单行匹配
    
        re.sub(正则表达式, 替换内容, 字符串)
      对应练习
    
    # 1 提取出python
    '''
    key = 'javapythonc++php'
    
    re.findall('python',key)
    re.findall('python',key)[0]
    '''
    # 2 提取出 hello word
    '''
    key = '<html><h1>hello word</h1></html>'
    print(re.findall('<h1>.*</h1>', key))
    print(re.findall('<h1>(.*)</h1>', key))
    print(re.findall('<h1>(.*)</h1>', key)[0])
    '''
    # 3 提取170
    '''
    key = '这个女孩身高170厘米'
    print(re.findall('d+', key)[0])
    '''
    # 4 提取出http://和https://
    '''
    key = 'http://www.baidu.com and https://www.cnblogs.com'
    print(re.findall('https?://', key))
    '''
    # 5 提取出 hello
    '''
    key = 'lalala<hTml>hello</HtMl>hahaha'   # 输出的结果<hTml>hello</HtMl>
    print(re.findall('<[hH][tT][mM][lL]>.*[/hH][tT][mM][lL]>',key))
    '''
    # 6 提取hit. 贪婪模式;尽可能多的匹配数据
    '''
    key = 'qiang@hit.edu.com'                # 加?是贪婪匹配,不加?是非贪婪匹配
    print(re.findall('h.*?.', key))
    '''
    # 7 匹配出所有的saas和sas
    '''
    key = 'saas and sas and saaas'
    print(re.findall('sa{1,2}s',key))
    '''
    # 8 匹配出 i 开头的行
    '''
    key = """fall in love with you
    i love you very much 
    i love she
    i love her
    """
    print(re.findall('^i.*', key, re.M))
    '''
    # 9 匹配全部行
    '''
    key = """
    <div>细思极恐
    你的队友在看书,
    你的闺蜜在减肥,
    你的敌人在磨刀,
    隔壁老王在练腰.
    </div>
    """
    print(re.findall('.*', key, re.S))
    '''

      项目实例

    需求1 :爬取糗事百科指定页面的糗图,并将其保存到指定文件夹中

    import re
    import os
    import requests
    
    if not os.path.exists('qiutu'):
        os.mkdir('qiutu')
    
    url = 'https://www.qiushibaike.com/pic'
    
    heards = {
    'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36'
    }
    response = requests.get(url=url, headers=heards)
    
    page_text = response.text
    
    # 正则匹配出图片的src
    # <div class="thumb">
    #
    # <a href="/article/121360019" target="_blank">
    # <img src="//pic.qiushibaike.com/system/pictures/12136/121360019/medium/0TOTENVGL8R9KQFD.jpg" alt="这位同学老哥千里送人头">
    # </a>
    #
    # </div>
    img_url_list = re.findall('<div class="thumb">.*?<img src="(.*?)".*?>.*?</div>', page_text, re.S)
    
    for img_url in img_url_list:
        img_url = "https:" + img_url
    
        res = requests.get(url=img_url, headers = heards)
        img = res.content
    
        # 持久化处理
        imgName = img_url.split('/')[-1]
        filePath = './qiutu/' + imgName          #    ./qiutu/ 
        with open(filePath, 'wb') as f:
            f.write(img)
    

      

    二 Xpath解析

     1 回顾:

    <html lang="en">
    <head>
    	<meta charset="UTF-8" />
    	<title>测试bs4</title>
    </head>
    <body>
    	<div>
    		<p>百里守约</p>
    	</div>
    	<div class="song">
    		<p>李清照</p>
    		<p>王安石</p>
    		<p>苏轼</p>
    		<p>柳宗元</p>
    		<a href="http://www.song.com/" title="赵匡胤" target="_self">
    			<span>this is span</span>
    		宋朝是最强大的王朝,不是军队的强大,而是经济很强大,国民都很有钱</a>
    		<a href="" class="du">总为浮云能蔽日,长安不见使人愁</a>
    		<img src="http://www.baidu.com/meinv.jpg" alt="" />
    	</div>
    	<div class="tang">
    		<ul>
    			<li><a href="http://www.baidu.com" title="qing">清明时节雨纷纷,路上行人欲断魂,借问酒家何处有,牧童遥指杏花村</a></li>
    			<li><a href="http://www.163.com" title="qin">秦时明月汉时关,万里长征人未还,但使龙城飞将在,不教胡马度阴山</a></li>
    			<li><a href="http://www.126.com" alt="qi">岐王宅里寻常见,崔九堂前几度闻,正是江南好风景,落花时节又逢君</a></li>
    			<li><a href="http://www.sina.com" class="du">杜甫</a></li>
    			<li><a href="http://www.dudu.com" class="du">杜牧</a></li>
    			<li><b>杜小月</b></li>
    			<li><i>度蜜月</i></li>
    			<li><a href="http://www.haha.com" id="feng">凤凰台上凤凰游,凤去台空江自流,吴宫花草埋幽径,晋代衣冠成古丘</a></li>
    		</ul>
    	</div>
    </body>
    </html>
    

      练习

    属性定位:
        #找到class属性值为song的div标签
        //div[@class="song"] 
    层级&索引定位:
        #找到class属性值为tang的div的直系子标签ul下的第二个子标签li下的直系子标签a
        //div[@class="tang"]/ul/li[2]/a
    逻辑运算:
        #找到href属性值为空且class属性值为du的a标签
        //a[@href="" and @class="du"]
    模糊匹配:
        //div[contains(@class, "ng")]
        //div[starts-with(@class, "ta")]
    取文本:
        # /表示获取某个标签下的文本内容
        # //表示获取某个标签下的文本内容和所有子标签下的文本内容
        //div[@class="song"]/p[1]/text()
        //div[@class="tang"]//text()
    取属性:
        //div[@class="tang"]//li[2]/a/@href
    

      2 Xpath的使用

    1.下载:pip install lxml
    2.导包:from lxml import html
        etree = html.etree 3.将html文档或者xml文档转换成一个etree对象,然后调用对象中的方法查找指定的节点   3.1 本地文件:tree = etree.parse(文件名) tree.xpath("xpath表达式")   3.2 网络数据:tree = etree.HTML(网页内容字符串) tree.xpath("xpath表达式")

      

      项目实例

    需求2:Xpath解析boss招聘网站

    import os
    import requests
    from lxml import etree
    
    if not os.path.exists('boss'):
        os.mkdir('boss')
    
    job = input('请输入job名')
    
    headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36'
    }
    
    url = 'https://www.zhipin.com/job_detail/?'
    
    params = {
        'query':job
    }
    
    response = requests.get(url=url, params=params, headers=headers)
    page_text = response.text
    
    # 解析
    # 1 实例化一个etree对象,然后将页面数据封装到该对象
    
    tree = etree.HTML(page_text)
    # 2 调用 etree 对象中的Xpath函数实现解析
    li_list = tree.xpath('//*[@id="main"]/div/div[3]/ul/li')
    
    for el in li_list:
        url_list = el.xpath('./div/div[1]/h3/a/@href')[0]
        url = 'https://www.zhipin.com' + url_list
    
        # 第二页面发请求
        second_page = requests.get(url=url, headers=headers)
        second_page_detail = second_page.text
    
        # 建立第二页面的tree
        tree1 = etree.HTML(second_page_detail)
    
        jobName = tree1.xpath('//div[@class="info-primary"]/div[2]/h1/text()')[0]
        detail = tree1.xpath('//div[@class="info-primary"]/p//text()')[0]
        company = tree1.xpath('//div[@class="info-company"]/h3/a/text()')[0]
        job_sec = tree1.xpath('//div[@class="job-sec"]/h3/text()')[0]
        job_sec_detail = tree1.xpath('//div[@class="job-sec"]/div/text()')[0]
    
    
        detail_total = jobName + '
    ' + detail + '
    ' + company + '
    ' + job_sec + '
    ' + job_sec_detail
    
        # 持久化
        jobPath = './boss/' + jobName
        with open(jobPath, 'w', encoding='utf-8') as f:
            f.write(detail_total)

    三 BeautifulSoup解析

     环境安装

    - 需要将pip源设置为国内源,阿里源、豆瓣源、网易源等
       - windows
        (1)打开文件资源管理器(文件夹地址栏中)
        (2)地址栏上面输入 %appdata%
        (3)在这里面新建一个文件夹  pip
        (4)在pip文件夹里面新建一个文件叫做  pip.ini ,内容写如下即可
            [global]
            timeout = 6000
            index-url = https://mirrors.aliyun.com/pypi/simple/
            trusted-host = mirrors.aliyun.com
    
       - linux
        (1)cd ~
        (2)mkdir ~/.pip
        (3)vi ~/.pip/pip.conf
        (4)编辑内容,和windows一模一样
    
    
    - 需要安装:pip install bs4
         bs4在使用时候需要一个第三方库,把这个库也安装一下
         pip install lxml 

     基础使用

    导包:from bs4 import BeautifulSoup
    
    
    使用方式:可以将一个html文档,转化为BeautifulSoup对象,然后通过对象的方法或者属性去查找指定的节点内容
            (1)转化本地文件:
                 - soup = BeautifulSoup(open('本地文件'), 'lxml')
            (2)转化网络文件:
                 - soup = BeautifulSoup('字符串类型或者字节类型', 'lxml')
            (3)打印soup对象显示内容为html文件中的内容
    

    BeautifulSoup基础操作

        (1)根据标签名查找
            - soup.a   只能找到第一个符合要求的标签
        (2)获取属性
            - soup.a.attrs  获取a所有的属性和属性值,返回一个字典
            - soup.a.attrs['href']   获取href属性
            - soup.a['href']   也可简写为这种形式
        (3)获取内容
            - soup.a.string
            - soup.a.text
            - soup.a.get_text()
           【注意】如果标签还有标签,那么string获取到的结果为None,而其它两个,可以获取文本内容
        (4)find:找到第一个符合要求的标签
            - soup.find('a')  找到第一个符合要求的
            - soup.find('a', title="xxx")
            - soup.find('a', alt="xxx")
            - soup.find('a', class_="xxx")
            - soup.find('a', id="xxx")
        (5)find_all:找到所有符合要求的标签
            - soup.find_all('a')
            - soup.find_all(['a','b']) 找到所有的a和b标签
            - soup.find_all('a', limit=2)  限制前两个
        (6)根据选择器选择指定的内容
                   select:soup.select('#feng')
            - 常见的选择器:标签选择器(a)、类选择器(.)、id选择器(#)、层级选择器
                - 层级选择器:
                    div .dudu #lala .meme .xixi  下面好多级
                    div > p > a > .lala          只能是下面一级
            【注意】select选择器返回永远是列表,需要通过下标提取指定的对象
    

    项目需求:使用bs4实现将诗词名句网站中三国演义小说的每一章的内容爬去到本地磁盘进行存储   http://www.shicimingju.com/book/sanguoyanyi.html 

    import requests
    from bs4 import BeautifulSoup
    
    headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36'
    }
    
    # 获取内容函数 def get_content(url): res = requests.get(url=url, headers=headers).text soup = BeautifulSoup(res, 'lxml') return soup.find('div', class_='chapter_content').text # 第一次请求 url = 'http://www.shicimingju.com/book/sanguoyanyi.html' response = requests.get(url=url, headers=headers).text # Beautiful实例化 soup = BeautifulSoup(response, 'lxml') # 解析 list = soup.select('.book-mulu > ul > li > a') fp = open('sanguo.txt', 'w', encoding='utf-8') for li in list: title = li.text # 获取标题 con_url = 'http://www.shicimingju.com' + li['href'] # 获取url content = get_content(con_url) # 获取标题下的内容(二次请求) fp.write(title + ' ' + content) # 写入文件 print(title+'被下载成功') fp.close()
  • 相关阅读:
    线程同步 –Mutex和Semaphore
    线程同步 –AutoResetEvent和ManualResetEvent
    线程同步 – lock和Monitor
    .NET垃圾回收 – 非托管资源
    .NET垃圾回收 – 原理浅析
    反射简介—C#特性和反射
    反射简介—类型反射和晚期绑定
    Django REST framework 第一章 Serialization
    Django REST framework 简介
    Python Django 实用小案例2
  • 原文地址:https://www.cnblogs.com/a438842265/p/10145544.html
Copyright © 2011-2022 走看看