欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

requests在python中發(fā)送請(qǐng)求的實(shí)例講解

 更新時(shí)間:2021年02月17日 12:06:24   作者:小妮淺淺  
在本篇文章里小編給大家整理的是一篇關(guān)于requests在python中發(fā)送請(qǐng)求的實(shí)例講解內(nèi)容,有興趣的朋友們可以測(cè)試學(xué)習(xí)下。

當(dāng)我們想給服務(wù)器發(fā)送一些請(qǐng)求時(shí),可以選擇requests庫來實(shí)現(xiàn)。相較于其它庫而言,這種庫的使用還是非常適合新手使用的。本篇要講的是requests.get請(qǐng)求方法,這里需要先對(duì)get請(qǐng)求時(shí)的一些參數(shù)進(jìn)行學(xué)習(xí),在掌握了基本的用法后,可以就下面的requests.get請(qǐng)求實(shí)例進(jìn)一步的探究。

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

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

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

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

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

任何時(shí)候進(jìn)行了類似 requests.get() 的調(diào)用,你都在做兩件主要的事情。其一,你在構(gòu)建一個(gè) Request對(duì)象, 該對(duì)象將被發(fā)送到某個(gè)服務(wù)器請(qǐng)求或查詢一些資源。其二,一旦 requests 得到一個(gè)從服務(wù)器返回的響應(yīng)就會(huì)產(chǎn)生一個(gè) Response 對(duì)象。該響應(yīng)對(duì)象包含服務(wù)器返回的所有信息,也包含你原來創(chuàng)建的 Request 對(duì)象。如下是一個(gè)簡(jiǎn)單的請(qǐng)求,從 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ù)器的請(qǐng)求的頭部,我們可以簡(jiǎn)單地訪問該請(qǐng)求,然后是該請(qǐng)求的頭部:

>>> r.request.headers

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

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

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

發(fā)送get請(qǐng)求

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

# 接口地址
url = 'http://v.juhe.cn/historyWeather/citys'
# 請(qǐng)求的參數(shù)數(shù)據(jù)
da = {'key':'61e0c8a6d9614382afbaaf35dbd3ec6','province_id':'4'}
# 發(fā)送請(qǐng)求
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中發(fā)送請(qǐng)求的實(shí)例講解的文章就介紹到這了,更多相關(guān)requests在python中如何發(fā)送請(qǐng)求內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論