一、常規用法
requests是一個python第三方庫,提供了訪問HTTP資源的方法。requests.get是最常用的方法之一,通常用來獲取URL地址的內容(HTML頁面、API接口的返回結果等),其基礎用法如下:
import requests
url = 'http://www.example.com'
response = requests.get(url)
print(response.content.decode('utf-8'))
上述代碼中,我們引入requests庫,設置URL地址為’http://www.example.com’,使用requests.get方法獲取其內容,並通過response.content獲取二進制數據源,使用decode(‘utf-8’)將其解碼為utf-8編碼的字符串內容,並打印出來。
除此之外,requests.get方法還提供了更多的參數。
二、請求參數
1、params參數
params參數可以在HTTP請求中添加查詢參數,形式為字典或字符串的元組列表。
import requests
url = 'http://www.example.com'
params = {'key1': 'value1', 'key2': 'value2'}
response = requests.get(url, params=params)
print(response.url)
上述代碼中,我們設置了params參數為一個字典{‘key1’: ‘value1’, ‘key2’: ‘value2’},當requests.get方法發起HTTP請求時,會將其作為查詢參數加到URL後面,形成’http://www.example.com?key1=value1&key2=value2’的請求URL,並打印出來。
2、headers參數
headers參數可以設置HTTP請求的頭部信息,形式為字典。
import requests
url = 'http://www.example.com'
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
response = requests.get(url, headers=headers)
print(response.status_code)
上述代碼中,我們設置了headers參數為一個字典,其中User-Agent字段模擬了Chrome瀏覽器的請求頭,請求’http://www.example.com’,並打印出HTTP請求的狀態碼。
3、cookies參數
cookies參數可以設置HTTP請求的cookies,形式為字典。
import requests
url = 'http://www.example.com'
cookies = {'name': 'value'}
response = requests.get(url, cookies=cookies)
print(response.cookies)
上述代碼中,我們設置了cookies參數為一個字典,其中name字段的值為value,請求’http://www.example.com’,並打印出HTTP響應的cookies信息。
三、響應參數
1、text參數
text參數返回HTTP響應的內容,形式為字符串。
import requests
url = 'http://www.example.com'
response = requests.get(url)
print(response.text)
上述代碼中,我們發起了一個GET請求,獲取’http://www.example.com’的響應內容,並使用response.text獲取並打印出來。
2、content參數
content參數返回HTTP響應的二進制數據源,形式為bytes。
import requests
url = 'http://www.example.com'
response = requests.get(url)
print(response.content)
上述代碼中,我們發起了一個GET請求,獲取’http://www.example.com’的響應二進制數據源,並使用response.content獲取並打印出來。
3、status_code參數
status_code參數返回HTTP響應的狀態碼,形式為整數。
import requests
url = 'http://www.example.com'
response = requests.get(url)
print(response.status_code)
上述代碼中,我們發起了一個GET請求,獲取’http://www.example.com’的響應狀態碼,並使用response.status_code獲取並打印出來。
結束語
requests.get是requests庫最常用的方法之一,掌握其基本和高級用法,在數據獲取與處理中將發揮重要作用。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/187030.html