iT邦幫忙

2024 iThome 鐵人賽

DAY 8
0

requests 函式庫是 Python 外部函式庫,具備了 GET、POST...等各種 request 用法,透過 requests 能夠輕鬆抓取網頁的資料,這篇會介紹 requests 函式庫的基本用法。

安裝 requests 模組

$pip install requests

引入

import requests

requests 的 HTTP 方法

請求伺服器提供資源可用的功能選項

# GET :獲取網頁內容, GET 如果有提交參數,其參數是放在標頭中傳送 (公開)
r = requests.get(url [, params])

# POST :提交請求, POST 如果有提交參數,則是放在內容中傳送 (隱密)
r = requests.post(url [, data])

# PUT : 提供最新內容
r = requests.put(url [, data])

# DELETE : 刪除指定的資源
r = requests.delete(url)

# HEAD : 提供資源的回應標頭 ( 不含內容 )
r = requests.head(url)

# OPTIONS : 請求伺服器提供資源可用的功能選項
r = requests.options(url)

傳遞參數

requests 在使用方法時,有時候也會加入指定的參數,以下為常用參數 :

  • params ( GET 使用 ) : 傳遞網址參數 ( dict )
  • data ( POST 使用 ) : 傳遞網址參數 ( dict )
  • headers : HTTP 的 headers 資訊 ( 可模擬不同的瀏覽器 )
  • cookies : 設定 Request 中的 cookie ( dict )

接下來試試看,使用 get 的方式發送 request,並加入 params 參數 => get 範例網址
https://ithelp.ithome.com.tw/upload/images/20240817/20168345SIAF7YQ3Ii.png

Response 物件的屬性與方法

當伺服器收到 requests HTTP 所發出的請求後,會傳回一個 Response 物件,物件裡包含伺服器回應的訊息資訊,以下為常用方法 :

  • url : 資源的 URL 位址
  • content : 回應訊息的內容 ( bytes )
  • text : 回應訊息的內容字串 ( str )
  • raw : 原始回應訊息串流 ( bytes )
  • status_code : 回應的狀態碼 ( int )
  • encoding : 回應訊息的編碼
  • headers : 回應訊息的標頭 ( dict )
  • cookies : 回應訊息的 cookies ( dict )
  • history : 請求歷史 ( list )
  • json() : 將回應訊息進行 JSON 解碼後回傳 ( dict )
  • rasise_for_status() : 檢查是否有例外發生,如果有就拋出例外

處理回應:

當使用 requests 進行 HTTP 請求時,伺服器的回應(即回傳的資料)可以通過「status_code」讀取網頁的回應狀態代碼,知道網頁的狀態

HTTP 狀態代碼

https://ithelp.ithome.com.tw/upload/images/20240817/20168345Tuh9TIXwVQ.png
圖源

假設讀取一個不存在的網頁,然後判斷 status_code 是否等於 404,則印出「找不到網頁」的文字
https://ithelp.ithome.com.tw/upload/images/20240817/20168345c9L4rReM83.png

爬取第一個靜態網頁內容

import requests

# 使用 get 方法 ,獲取輔大首頁內容
web = requests.get('https://www.fju.edu.tw/')

# 讀取並印出 text 屬性
print(web.text)
圖示 :

https://ithelp.ithome.com.tw/upload/images/20240817/201683451n7781NQhL.png

參考資料 :

https://steam.oxxostudio.tw/category/python/spider/requests.html
https://utrustcorp.com/python-requests/
https://yhhuang1966.blogspot.com/2020/06/python-requests-beautifulsoup.html


上一篇
[Python] ThreadPoolExecutor
下一篇
[Python] Beautiful Soup
系列文
一些Python可以做的事19
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言