溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

使用requests怎么在python項(xiàng)目中發(fā)送請求

發(fā)布時(shí)間:2021-02-18 14:29:51 來源:億速云 閱讀:146 作者:Leah 欄目:開發(fā)技術(shù)

這篇文章將為大家詳細(xì)講解有關(guān)使用requests怎么在python項(xiàng)目中發(fā)送請求,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個(gè)參考,希望大家閱讀完這篇文章后對相關(guān)知識有一定的了解。

1、get請求的部分參數(shù)

(1) url(請求的url地址,必需 )

import requests
url="http://www.baidu.com"
resp=requests.get(url)#向url對應(yīng)的服務(wù)器發(fā)送相應(yīng)的get請求,獲得對應(yīng)的相應(yīng) 。

(2)headers參數(shù) 請求頭,可選

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請求實(shí)例

任何時(shí)候進(jìn)行了類似 requests.get() 的調(diào)用,你都在做兩件主要的事情。其一,你在構(gòu)建一個(gè) Request對象, 該對象將被發(fā)送到某個(gè)服務(wù)器請求或查詢一些資源。其二,一旦 requests 得到一個(gè)從服務(wù)器返回的響應(yīng)就會(huì)產(chǎn)生一個(gè) Response 對象。該響應(yīng)對象包含服務(wù)器返回的所有信息,也包含你原來創(chuàng)建的 Request 對象。如下是一個(gè)簡單的請求,從 Wikipedia 的服務(wù)器得到一些非常重要的信息:

>>> r = requests.get('http://en.wikipedia.org/wiki/Monty_Python')

如果想訪問服務(wù)器返回給我們的響應(yīng)頭部信息,可以這樣做:

>>> 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'}

然而,如果想得到發(fā)送到服務(wù)器的請求的頭部,我們可以簡單地訪問該請求,然后是該請求的頭部:

>>> r.request.headers

{'Accept-Encoding': 'identity, deflate, compress, gzip',

'Accept': '*/*', 'User-Agent': 'python-requests/0.13.1'}

內(nèi)容擴(kuò)展:

發(fā)送get請求

# 導(dǎo)入requests模塊
import requests

# 接口地址
url = 'http://v.juhe.cn/historyWeather/citys'
# 請求的參數(shù)數(shù)據(jù)
da = {'key':'61e0c8a6d9614382afbaaf35dbd3ec6','province_id':'4'}
# 發(fā)送請求
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'])

關(guān)于使用requests怎么在python項(xiàng)目中發(fā)送請求就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI