requests在python中如何發送請求
本文教程操作環境:windows7系統、Python3.9.1,DELLG3電腦。
1、get請求的部分參數
(1)url(請求的url地址,必需)
importrequests
url="http://www.baidu.com"
resp=requests.get(url)#向url對應的服務器發送相應的get請求,獲得對應的相應。
(2)headers參數(請求頭,可選)
importrequests
url=r"https://www.baidu.com/s"
Headers={"User-Agent":"Mozilla/5.0(WindowsNT10.0;Win64;x64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/71.0.3578.98Safari/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':
'HITfromcp1006.eqiad.wmnet,MISSfromcp1010.eqiad.wmnet','content-encoding':
'gzip','age':'3080','content-language':'en','vary':'Accept-Encoding,Cookie',
'server':'Apache','last-modified':'Wed,13Jun201201:33:50GMT',
'connection':'close','cache-control':'private,s-maxage=0,max-age=0,
must-revalidate','date':'Thu,14Jun201212:59:39GMT','content-type':
'text/html;charset=UTF-8','x-cache-lookup':'HITfromcp1006.eqiad.wmnet:3128,
MISSfromcp1010.eqiad.wmnet:80'}
然而,如果想得到發送到服務器的請求的頭部,我們可以簡單地訪問該請求,然后是該請求的頭部:
>>>r.request.headers
{'Accept-Encoding':'identity,deflate,compress,gzip',
'Accept':'*/*','User-Agent':'python-requests/0.13.1'}
以上就是requests在python中發送請求的方法,大家對于基礎的get參數有所了解后,可以自己動手試著給服務器發送請求,看看能否獨立完成相關的操作。更多Python學習教程請關注IT培訓機構:千鋒教育。