當我們想給服務器發送一些請求時,可以選擇requests庫來實現。相較于其它庫而言,這種庫的使用還是非常適合新手使用的。本篇要講的是requests.get請求方法,這里需要先對get請求時的一些參數進行學習,在掌握了基本的用法后,可以就下面的requests.get請求實例進一步的探究。
1、get請求的部分參數
(1) url(請求的url地址,必需 )
import requests
url="http://www.baidu.com"
resp=requests.get(url)#向url對應的服務器發送相應的get請求,獲得對應的相應 。
(2)headers參數 請求頭,可選
import requests
url=r"https://www.baidu.com/s"
Headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36"
}
response=requests.get(url=url,headers=Headers)
2、requests.get請求實例
任何時候進行了類似 requests.get() 的調用,你都在做兩件主要的事情。其一,你在構建一個 Request對象, 該對象將被發送到某個服務器請求或查詢一些資源。其二,一旦 requests 得到一個從服務器返回的響應就會產生一個 Response 對象。該響應對象包含服務器返回的所有信息,也包含你原來創建的 Request 對象。如下是一個簡單的請求,從 Wikipedia 的服務器得到一些非常重要的信息:
>>> r = requests.get('http://en.wikipedia.org/wiki/Monty_Python')
如果想訪問服務器返回給我們的響應頭部信息,可以這樣做:
>>> r.headers
{'content-length': '56170', 'x-content-type-options': 'nosniff', 'x-cache':
'HIT from cp1006.eqiad.wmnet, MISS from cp1010.eqiad.wmnet', 'content-encoding':
'gzip', 'age': '3080', 'content-language': 'en', 'vary': 'Accept-Encoding,Cookie',
'server': 'Apache', 'last-modified': 'Wed, 13 Jun 2012 01:33:50 GMT',
'connection': 'close', 'cache-control': 'private, s-maxage=0, max-age=0,
must-revalidate', 'date': 'Thu, 14 Jun 2012 12:59:39 GMT', 'content-type':
'text/html; charset=UTF-8', 'x-cache-lookup': 'HIT from cp1006.eqiad.wmnet:3128,
MISS from cp1010.eqiad.wmnet:80'}
然而,如果想得到發送到服務器的請求的頭部,我們可以簡單地訪問該請求,然后是該請求的頭部:
>>> r.request.headers
{'Accept-Encoding': 'identity, deflate, compress, gzip',
'Accept': '*/*', 'User-Agent': 'python-requests/0.13.1'}
內容擴展:
發送get請求
# 導入requests模塊
import requests
# 接口地址
url = 'http://v.juhe.cn/historyWeather/citys'
# 請求的參數數據
da = {'key':'61e0c8a6d9614382afbaaf35dbd3ec6','province_id':'4'}
# 發送請求
r = requests.get(url,params=da)
# 獲取返回的json
js = r.json()
print(js)
print(js['resultcode'])
print(js['reason'])
print(js['result'])
print(js['error_code'])
到此這篇關于requests在python中發送請求的實例講解的文章就介紹到這了,更多相關requests在python中如何發送請求內容請搜索腳本之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:- python爬蟲之利用Selenium+Requests爬取拉勾網
- Python requests timeout的設置
- python+requests+pytest接口自動化的實現示例
- python3 解決requests出錯重試的問題
- Python requests庫參數提交的注意事項總結
- python urllib.request模塊的使用詳解
- python requests完成接口文件上傳的案例
- python爬取豆瓣電影排行榜(requests)的示例代碼
- python 實現Requests發送帶cookies的請求
- python軟件測試Jmeter性能測試JDBC Request(結合數據庫)的使用詳解
- python requests庫的使用
- python實現文件+參數發送request的實例代碼
- Python爬蟲基礎之requestes模塊