數據解析之正則解析


一,介紹

大多數情況下的需求,我們都會指定去使用聚焦爬蟲,也就是爬取頁面中指定部分的數據值,而不是整個頁面的數據。

因此數據爬取的流程為:

  1. 指定url
  2. 基於requests模塊發起請求
  3. 獲取響應中的數據
  4. 數據解析
  5. 進行持久化存儲

二,正則解析數據

常用正則表達式回顧:

單字符:
        . : 除換行以外所有字符
        [] :[aoe] [a-w] 匹配集合中任意一個字符
        \d :數字  [0-9]
        \D : 非數字
        \w :數字、字母、下划線、中文
        \W : 非\w
        \s :所有的空白字符包,括空格、制表符、換頁符等等。等價於 [ \f\n\r\t\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(正則表達式, 替換內容, 字符串)
正則復習
import re
#提取出python
key="javapythonc++php"
re.findall('python',key)[0]
#####################################################################
#提取出hello world
key="<html><h1>hello world<h1></html>"
re.findall('<h1>(.*)<h1>',key)[0]
#####################################################################
#提取170
string = '我喜歡身高為170的女孩'
re.findall('\d+',string)
#####################################################################
#提取出http://和https://
key='http://www.baidu.com and https://boob.com'
re.findall('https?://',key)
#####################################################################
#提取出hello
key='lalala<hTml>hello</HtMl>hahah' #輸出<hTml>hello</HtMl>
re.findall('<[Hh][Tt][mM][lL]>(.*)</[Hh][Tt][mM][lL]>',key)
#####################################################################
#提取出hit. 
key='bobo@hit.edu.com'#想要匹配到hit.
re.findall('h.*?\.',key)
#####################################################################
#匹配sas和saas
key='saas and sas and saaas'
re.findall('sa{1,2}s',key)
#####################################################################
#匹配出i開頭的行
string = '''fall in love with you
i love you very much
i love she
i love her'''

re.findall('^.*',string,re.M)
#####################################################################
#匹配全部行
string1 = """<div>靜夜思
窗前明月光
疑是地上霜
舉頭望明月
低頭思故鄉
</div>"""

re.findall('.*',string1,re.S)
正則練習

ex:項目需求:爬取糗事百科指定頁面的糗圖,並將其保存到指定文件夾中 

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import requests
import re
import os
if __name__ == "__main__":
     url = 'https://www.qiushibaike.com/pic/%s/'
     headers={
         'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
     }
     #指定起始也結束頁碼
     page_start = int(input('enter start page:'))
     page_end = int(input('enter end page:'))

     #創建文件夾
     if not os.path.exists('images'):
         os.mkdir('images')
     #循環解析且下載指定頁碼中的圖片數據
     for page in range(page_start,page_end+1):
         print('正在下載第%d頁圖片'%page)
         new_url = format(url % page)
         response = requests.get(url=new_url,headers=headers)

         #解析response中的圖片鏈接
         e = '<div class="thumb">.*?<img src="(.*?)".*?>.*?</div>'
         pa = re.compile(e,re.S)
         image_urls = pa.findall(response.text)
          #循環下載該頁碼下所有的圖片數據
         for image_url in image_urls:
             image_url = 'https:' + image_url
             image_name = image_url.split('/')[-1]
             image_path = 'images/'+image_name

             image_data = requests.get(url=image_url,headers=headers).content
             with open(image_path,'wb') as fp:
                 fp.write(image_data)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM