Python---Requests、BeautifulSoup

一、requests庫的詳解:

request參數:

requests.request(
    method,   # 請求方式 get post put等
    url,      # 訪問地址
    params,   # 在url上傳遞的參數,以字典的形式{"date":"today"}傳參,get方式會用到(xxx.com/news?date=today)
    data,     # 在請求體裏傳遞的數據,post方式會用到,以字典的方式傳參,還可以以字符串的形式穿遞
              # 類似"user=alex&pwd=2333", 傳字典最後也會轉換爲字符串;也可以上傳文件。
    json,     # 在請求體裏面傳遞數據,會自動執行json.dumps方法,會變成字符串"{'name':'alex'}"。
    headers,  # 請求頭,以字典的形式傳參
    cookies,  # 就是cookie, cookie在請求頭中
    files,    # 進行上傳文件, {"f1": open("s1.py" ,"rb")},value既可以是文件對象也可以是文件內容
              # 還可以以元組的形式指定上傳到服務器的文件名{"f1": ("文件名", open("s1.py" ,"rb" ,'application/vnd.ms-excel'))}    
              # 如果是一個文件對象會在內部調用read方法。
    auth,     # 認證,適用於有彈窗要求輸入用戶名和密碼,實際上是在請求頭加了一條數據(用戶名和密碼)
              # auth = HTTPBasicAuth("用戶名","密碼")  
    timeout,  # 超時時間, 也可以是元組的形式(發送時間,讀的時間)
    allow _redirects,  #  是否進行重定向跳轉
    proxies,  # 代理,字典的形式 {"http" : "127.01.1.0"}
    stream,   # stream=True  代表是流的處理  當下載文件過大的時候用
    verify,   # 是否使用證書
    cert      # 證書文件, cert ="證書文件路徑" 元組形式傳參(***.cert,***.key)
)

※:request.get()和request.post()在底層調用的都是requests.requests()。

※:當傳參數時出現字典裏套字典的情況時用json,其他時候二者都可。

流式下載:

from contextlib import closing
    with closing(requests.get('http://httpbin.org/get', stream=True)) as r:
    # 在此處理響應。
        for i in r.iter_content():
            print(i)

基於session的請求

import requests

session = requests.Session()
#  用法和requests一樣
response = session.get(url="http://dig.chouti.com/help/service")  

Response響應的參數:

response.status_code   # 狀態碼
        .headers       # 響應頭
        .encoding      # 編碼
        .apparent_encoding   # 可接受的編碼
        .text          # 以文本形式返回響應內容。
        .content       # 以字節的形式返回響應內容。以字節的形式返回響應內容。
        .cookies.get_dict()       # cookies屬性
        .url           # 用於返回響應的url.由於重定向的存在,可能會出現我們請求的地址和響應的地址並不 一樣的情況.
        .json          # 處理 JSON 數據

二、BeautifulSoup庫的詳解

該模塊用於接收一個HTML或XML字符串,然後將其進行格式化,之後遍可以使用他提供的方法進行快速查找指定元素,從而使得在HTML或XML中查找指定元素變得簡單。

1. name,標籤名稱

tag = soup.find('a')
name = tag.name # 獲取

tag.name = 'span' # 設置

2. attr,標籤屬性

tag = soup.find('a')
tag.attrs.get("href")    # 獲取href

tag.attrs = {'ik':123} # 設置
tag.attrs['id'] = 'iiiii' # 設置

3. children,所有子標籤(換行也會拿到),返回的是一個迭代器。

body = soup.find('body')
body.children      #  所有子標籤
body.descendants   #  所有子子孫孫標籤

4. decode,轉換爲字符串(含當前標籤);decode_contents(不含當前標籤)

body = soup.find('body')
body.decode()
body.decode_contents()

5. encode,轉換爲字節(含當前標籤);encode_contents(不含當前標籤)

body = soup.find('body')
body.encode()
body.encode_contents()

6. find,獲取匹配的第一個標籤

#  找到第一個符合條件的對象,返回的是一個soup對象
soup.find('a')

# 找到一個a標籤,class=sisiter,text=Lacie,遞歸的去尋找
soup.find(name='a', attrs={'class': 'sister'}, recursive=True, text='Lacie')

7. find_all,獲取匹配的所有標籤

# find_all的用法和find一樣,但是有拓展,返回的是一個列表對象
soup.find_all(name='a', attrs={'class': 'sister'}, recursive=True, text='Lacie')
 
# ####### 列表 #######
soup.find_all(name=['a','div'])   # 找到name爲"a"或者爲"div"

# ####### 正則 #######
import re

rep = re.compile('^p')
soup.find_all(name=rep)     #  找到所有name符合正則表達式的

# ####### 方法篩選 #######
def func(tag):  #  tag是當前處理的標籤
  return tag.has_attr('class') and tag.has_attr('id')

soup.find_all(name=func)

8. has_attr,檢查標籤是否具有該屬性

tag = soup.find('a')
tag.has_attr('id')

9. get_text,獲取標籤內部文本內容

tag = soup.find('a')
tag.get_text('id')

10. select,select_one, CSS選擇器

soup.select("title")   # 找到title標籤
 
soup.select("#link")   # 找到id爲link的元素
 
soup.select("body a")  # 找到body標籤下所有的a標籤

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章