一、簡介
getone是一個多功能的網絡請求庫,它支持同步和異步請求,支持GET、POST和自定義方法,支持文件上傳和下載,支持HTTP和HTTPS,支持Cookie、代理、超時等等。使用getone,你可以輕鬆地發送HTTP/HTTPS請求並處理返回結果。
二、基本用法
1. 發送GET請求
import getone url = "https://api.github.com/" response = getone.get(url) print(response.status_code) # 輸出響應狀態碼 print(response.text) # 輸出響應內容
上面的代碼示例中,我們使用get函數發送了一個GET請求,並打印了響應狀態碼和響應內容。在這個URL中,我們可以得到GitHub API的根目錄。
2. 發送POST請求
import getone url = "https://httpbin.org/post" data = {'message': 'hello world'} response = getone.post(url, data=data) print(response.status_code) # 輸出響應狀態碼 print(response.json()) # 輸出響應JSON內容
上面的代碼示例中,我們使用post函數發送了一個POST請求,並打印了響應狀態碼和響應JSON內容。在這個URL中,我們可以得到一個完整的HTTP請求和響應的信息。
三、高級用法
1. 自定義請求頭
getone允許您自定義HTTP請求頭。只需將headers參數傳遞給get或post函數即可:
import getone url = "https://www.baidu.com" headers = {'User-Agent': 'Mozilla/5.0'} response = getone.get(url, headers=headers) print(response.status_code) # 輸出響應狀態碼 print(response.text) # 輸出響應內容
上面的代碼示例中,我們自定了User-Agent請求頭並獲取了百度首頁的內容。
2. 發送文件
通過POST方法發送文件,只需將files參數傳遞給post函數即可:
import getone url = "https://httpbin.org/post" files = {'file': open('example.txt', 'rb')} response = getone.post(url, files=files) print(response.status_code) # 輸出響應狀態碼 print(response.json()) # 輸出響應JSON內容
上面的代碼示例中,我們通過POST方法發送了一個文件,並獲得了服務器響應的JSON內容。
3. 超時設置
您可以通過timeout參數設置請求超時時間(秒):
import getone url = "https://www.163.com" response = getone.get(url, timeout=1) print(response.status_code) # 輸出響應狀態碼 print(response.text) # 輸出響應內容
上面的代碼示例中,我們通過timeout參數設置了請求超時時間為1秒。如果服務器在1秒內未對請求作出響應,則會拋出超時異常。
4. 代理設置
如果您需要通過代理服務器發送請求,請使用proxies參數:
import getone url = "https://www.google.com" proxies = {'https': 'https://127.0.0.1:1080'} response = getone.get(url, proxies=proxies) print(response.status_code) # 輸出響應狀態碼 print(response.text) # 輸出響應內容
上面的代碼示例中,我們配置了https協議下的代理服務器,並獲取了谷歌首頁的內容。
5. Cookie管理
getone提供了Cookie支持。您可以通過cookies參數設置Cookie,或通過cookiejar參數使用自定義CookieJar實例:
import getone import http.cookiejar url = "https://httpbin.org/cookies" cookies = dict(cookies_are='working') response = getone.get(url, cookies=cookies) print(response.status_code) # 輸出響應狀態碼 print(response.json()) # 輸出響應JSON內容 # 使用自定義CookieJar實例 cookie_jar = http.cookiejar.CookieJar() response = getone.get(url, cookiejar=cookie_jar) print(response.status_code) # 輸出響應狀態碼 print(response.json()) # 輸出響應JSON內容
上面的代碼示例中,我們演示了如何使用Cookie進行請求。
原創文章,作者:KUBXK,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/361028.html