1. 程式人生 > >Request模塊—數據解析工具

Request模塊—數據解析工具

https 啟動 yun 使用 基本語法 select star 新建 ast

一、爬蟲基本步驟

  • 指定URL信息
  • 發起請求
  • 獲取響應數據
  • 對響應數據進行數據解析
  • 持久化存儲

二、數據解析

1. 正則表達式

(1) 基本語法
1. 單字符:
    . : 除換行以外所有字符
    [] :[aoe] [a-w] 匹配集合中任意一個字符
    \d :數字  [0-9]
    \D : 非數字
    \w :數字、字母、下劃線、中文
    \W : 非\w
    \s :所有的空白字符包,括空格、制表符、換頁符等等。等價於 [ \f\n\r\t\v]。
    \S : 非空白
2. 數量修飾:
    * : 任意多次  >=0
    + : 至少1次   >=1
    ? : 可有可無  0次或者1次
    {m} :固定m次 hello{3,}
    {m,} :至少m次
    {m,n} :m-n次
3. 邊界:
    $ : 以某某結尾
    ^ : 以某某開頭
4. 分組:
    (ab)  
5. 貪婪模式: .*
6. 非貪婪(惰性)模式: .*?
7. 爬蟲正則
    re.I : 忽略大小寫
    re.M :多行匹配
    re.S :單行匹配  //爬蟲常用
    re.sub(正則表達式, 替換內容, 字符串)
(2) 相關案例
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='[email protected]'  # 想要匹配到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)

2. Beautifulsoup

(1) 環境安裝
- 需要將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
(2) 基礎使用
1. 使用流程:       
    - 導包:from bs4 import BeautifulSoup
    - 使用方式:可以將一個html文檔,轉化為BeautifulSoup對象,然後通過對象的方法或者屬性去查找指定的節點
    
2. 內容
    (1)轉化本地文件:
        - soup = BeautifulSoup(open('本地文件'), 'lxml')
    (2)轉化網絡文件:
        - soup = BeautifulSoup('字符串類型或者字節類型', 'lxml')
    (3)打印soup對象顯示內容為html文件中的內容
    
3. 基礎鞏固:
    (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選擇器返回永遠是列表,需要通過下標提取指定的對象

3. xpath

(1) 選取節點
表達式 描述
nodename 選取此節點的所有子節點
/ 從根節點選取
// 從匹配選擇的當前節點選擇文檔中的節點,而不考慮它們的位置
. 選取當前節點
.. 選取當前節點的父節點
@ 選取屬性
(2) 案例
路徑表達式 結果
bookstore 選取 bookstore 元素的所有子節點
/bookstore 選取根元素 bookstore;註釋:假如路徑起始於正斜杠( / )則此路徑始終代表到某元素的絕對路徑
bookstore/book 選取屬於 bookstore 的子元素的所有 book 元素
//book 選取所有 book 子元素,而不管它們在文檔中的位置
bookstore//book 選擇屬於 bookstore 元素的後代的所有 book 元素,而不管它們位於 bookstore 之下的什麽位置
//@lang 選取名為 lang 的所有屬性
(3) 謂語
表達式 結果
/bookstore/book[1] 選取屬於 bookstore 子元素的第一個 book 元素
/bookstore/book[last()] 選取屬於 bookstore 子元素的最後一個 book 元素
/bookstore/book[last()-1] 選取屬於 bookstore 子元素的倒數第二個 book 元素
/bookstore/book[position()<3] 選取最前面的兩個屬於 bookstore 元素的子元素的 book 元素
//title[@lang] 選取所有擁有名為 lang 的屬性的 title 元素
//title[@lang=‘eng‘] 選取所有 title 元素,且這些元素擁有值為 eng 的 lang 屬性
/bookstore/book[price>35.00] 選取 bookstore 元素的所有 book 元素,且其中的 price 元素的值須大於 35.00
/bookstore/book[price>35.00]/title 選取 bookstore 元素中的 book 元素的所有 title 元素,且其中的 price 元素的值須大於 35.00
(4) 選取位置節點
表達式 結果
* 匹配任何元素節點
@* 匹配任何元素屬性節點
node() 匹配任何類型的節點
路徑表達式 結果
/bookstore/* 選取bookstore元素的所有子元素
//* 選取文檔中的所有元素
//title[@*] 選取所有帶屬性的title元素
路徑表達式 結果
//book/title | //book/price 選取 book 元素的所有 title 和 price 元素
//title | //price 選取文檔中的所有 title 和 price 元素
/bookstore/book/title | //price 選取屬於 bookstore 元素的 book 元素的所有 title 元素,以及文檔中所有的 price 元素
(5) 基本案例
1. 屬性定位:
    #找到class屬性值為song的div標簽
    //div[@class="song"]
2. 層級&索引定位:
    #找到class屬性值為tang的div的直系子標簽ul下的第二個子標簽li下的直系子標簽a
    //div[@class="tang"]/ul/li[2]/a
3. 邏輯運算:
    #找到href屬性值為空且class屬性值為du的a標簽
    //a[@href="" and @class="du"]
4. 模糊匹配:
    //div[contains(@class, "ng")]
    //div[starts-with(@class, "ta")]
5. 取文本:
    # /表示獲取某個標簽下的文本內容
    # //表示獲取某個標簽下的文本內容和所有子標簽下的文本內容
    //div[@class="song"]/p[1]/text()
    //div[@class="tang"]//text()
6. 取屬性:
    //div[@class="tang"]//li[2]/a/@href

三、流程

1.下載:pip install lxml

2.導包:from lxml import etree

3.將html文檔或者xml文檔轉換成一個etree對象,然後調用對象中的方法查找指定的節點
    2.1 本地文件: tree = etree.parse(文件名)
                 tree.xpath("xpath表達式")
    2.2 網絡數據:tree = etree.HTML(網頁內容字符串)
                 tree.xpath("xpath表達式")
        
4.備註:
    安裝Chrome的xpath插件
    安裝xpath插件在瀏覽器中對xpath表達式進行驗證:可以在插件中直接執行xpath表達式
    將xpath插件拖動到谷歌瀏覽器拓展程序(更多工具)中,安裝成功
    啟動和關閉插件 ctrl + shift + x
    
5.xpath解析原理
- 實例化一個etree的對象,且將頁面源碼數據加載到該對象中    
- 調用etree對象中的xpath方法實現標簽定位和數據的提取    
- 在xpath函數中必須作用xpath表達式    
- xpath函數返回的一定是一個列表

Request模塊—數據解析工具