1. 程式人生 > 實用技巧 >requests和xpath筆記

requests和xpath筆記

Requests庫和xpath筆記

Requests安裝

pip install requests -i https://mirrors.aliyun.com/pypi/simple

核心函式

  • requests.requests() 所有請求方法的基本方法

    • method:str 指定請求方法, GET, POST, PUT, DELETE
    • url:str 請求的資源介面(API),在RESTful規範中即是URI
    • params:dict, 用於GET請求的查詢引數(Query String Params)
    • data:dict, 用於POST/PUT/DELETE請求的表單引數(Form Data)
    • json:dict, 用於上傳json資料的引數, 封裝到body(請求體)中。請求頭的Content-Type預設設定為 application/json
    • files:dict, 結構{'name':file-like-object|tuple},如果是tuple,則有三種情況:
      • ('filename', file-like-object)
      • ('filename', file-like-object, content_type)
      • ('filename', file-like-object, content_type, custom-headers)
        指定files用於上傳檔案,一般使用POST請求, 預設請求頭的Content-Type為multipart/form-data
        型別
    • headers/cookies:dict
    • proxies:dict, 設定代理
    • auth:tuple, 用於授權的使用者名稱和口令,形式{'username', 'pwd'}
  • requests.get() 發起GET請求, 查詢引數

    • 可用引數
      • url
      • params
      • json
      • headers/cookies/auth
  • requests.post()發起POST請求, 上傳/新增資料

    • 可用引數:
      • url
      • data/files
      • json
      • headers/cookies/auth
  • requests.put()發起PUT請求, 修改或更新資料

  • requests.patch()

    HTTP冪等性的問題,可能會出現重複,不推薦使用

  • requests.delete() 發起delete請求,刪除資料

requests.Response

以上的請求方法返回的物件型別是Response,物件常用的屬性如下

  • status_code 響應狀態碼
  • url 請求的url
  • headers:dict, 響應的頭,對應於urllib的響應物件的getheaders(), 但不包含cookie
  • cookies:可迭代的物件, 元素是Cookie類物件 (name, value, path)
  • text: 響應的文字資訊
  • content: 響應的位元組資料
  • encoding:響應資料的編碼字符集, 如utf-8, gbk, gb2312
  • json():如果響應資料型別為application/json, 則將響應的資料進行反序列化python得List或者dict物件(javascripte序列化和反序列化是JSON.stringify(obj)和JSON.parse(text))

資料解析方法之xpath

xpath 屬於xml/html解析資料的一種方式,基於元素的樹形結構(Node > Element)。選擇某一元素時,根據元素的路徑選擇, 如/hmtl/head/title獲取<title>標籤。安裝包pip install lxml

絕對路徑

從根標籤開始,按照tree結構依次向下查詢

/html/body/table/tbody/tr

相對路徑

相對路徑可以有以下寫法

  • 相對於整個文件
//img

查找出文件中所有的<img>標籤

  • 相對於當前節點
//table

假如當前節點是<table>,查詢他的<img>的路徑的寫法

.//img

資料提取

  • 提取文字
//title/text()
  • 提取屬性
//img/@href
  • 提取指定位置的元素
    獲取網頁中的資料型別與字符集,獲取第一個<meta>標籤
//meta[0]/@content
//meta[first()]/@content

獲取最後一個<meta>標籤

//meta[last()]/@content

獲取倒數第二個<meta>標籤

//meta[position()-2]/@content

獲取前三個<meta>標籤

//meta[position()<3]/@content

指定屬性條件

查詢class為circle-img<img>標籤

//img[@class="circle-img"]

在python 中的應用

安裝包pip install lxml