日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 综合教程 >内容正文

综合教程

python的requests用法详解

發(fā)布時(shí)間:2024/8/24 综合教程 33 生活家
生活随笔 收集整理的這篇文章主要介紹了 python的requests用法详解 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

python接口測試Requests用法詳解

Requests是一個(gè)Python語言寫的http相關(guān)設(shè)置或者請求的一個(gè)庫

安裝:pip install Requests或者pip3 install requests

使用的時(shí)候要import requests

http://httpbin.org/:這個(gè)鏈接可以用來檢查你請求的鏈接返回的內(nèi)容,輸出的是你請求的基本內(nèi)容,可以用來測試驗(yàn)證

get請求

1.基本get請求的寫法:

import requests

response = requests.get("http://httpbin.org/get")

print(response.text)

打印出你的請求頭,請求鏈接,IP地址等

2.參數(shù)的get請求(在鏈接的后面加上問號再加參數(shù))

Response = requests.get("http://httpbin.org/get?name=germey&age=22")

# 還有一種方式:就是先定義一個(gè)字典,然后調(diào)用get方法的時(shí)候,將字典賦值給給params參數(shù)

data = {

‘name’:’germey’,

‘age’:22

}

response = requests.get("http://httpbin.org/get",params=data)

print(response.text)

3.解析json

Json用來保存一些鍵值對組成的數(shù)據(jù),用于數(shù)據(jù)交換,也可用于前后端之間互相傳遞數(shù)據(jù),比如前端發(fā)起請求,調(diào)用接口,后端返回一串json數(shù)據(jù),處理數(shù)據(jù),渲染到頁面上。

Request模塊中也有解析json的方法:

import requests

response = requests.get("http://httpbin.org/get")

print(type(response.text))

print(response.json())

print(type(response.json()))

還可以這樣寫:

Import requests

Import json

response = requests.get("http://httpbin.org/get")
#和request.json()是一個(gè)意思,都是打印出一個(gè)字典數(shù)據(jù),這個(gè)json()方法也是調(diào)用了json的loads方法
print(json.loads(requests.test()))

4.獲取二進(jìn)制數(shù)據(jù)

一般用來下載圖片、視頻等

response = requests.get("http://github.com/favicon.ico")   #將要下載的圖片鏈接放這

print(type(response.text),type(response.content))  #類型分別是str和bytes

print(response.text)

print(response.content)     #獲取二進(jìn)制數(shù)據(jù)的方法

圖片的二進(jìn)制數(shù)據(jù)獲取到后怎么保存呢?

import requests

response = requests.get("http://github.com/favicon.ico")

with open("favicon.ico","wb") as f:

    f.write(response.content)

    f.close()

5.添加headers

有時(shí)候不加headers發(fā)請求的時(shí)候會直接被拒絕或者服務(wù)器錯(cuò)誤等,加上headers就可以了。

比如下面這段會報(bào)500錯(cuò)誤:

response = requests.get("https://www.zhihu.com/expiore")

print(response.text)

此時(shí)需要添加一個(gè)headers:

1 headers = {
2 
3 "User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36"
4 
5 }
6 
7 response = requests.get("https://www.zhihu.com/expiore",headers=headers)
8 
9 print(response.text)

基本post請求和get請求類似

6.需要的表單數(shù)據(jù)也用一個(gè)字典存起來給data參數(shù),headers和get方法一樣

Import requests

headers = {

"User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36"

}

data = {

‘name’:’germey’,

‘age’:22

}

# 需要注意和get方法不同的是如果有參數(shù)用的是data=而不是params=

response = requests.post("https://www.zhihu.com/expiore",data = data,headers = headers)

print(response.json())

響應(yīng)

7.response屬性

response = requests.post("https://www.jianshu.com")

print(type(response.status_code),response.status_code)

print(type(response.headers),response.headers)

print(type(response.cookies),response.cookies)

print(type(response.url),response.url)

print(type(response.history),response.history)   #歷史記錄

8.狀態(tài)碼判斷

1 response = requests.post("https://www.jianshu.com")
2 
3 exit() if not response.status_code==200 else print("request sucessfully")
4 
5 或者可以寫成:
6 
7 exit() if not response.status_code==request.codes.ok else print("request sucessfully")

狀態(tài)碼request.codes列表中的英文狀態(tài)對應(yīng)表

狀態(tài)碼

英文

100

("continue",)

101

("switching_protocols")

102

("processing",)

103

("checkpoint",)

122

("url_too_long","request_url_too_long")

200

("ok","okay","all_ok","all_good",\o/,"√")

201

("created",)

202

("accepted",)

203

("non_authoritative_info","non_authoritative_information")

204

("no_content",)

205

("reset_content","reset")

206

("partial_content","partial")

207

("multi_status","multiple_status","multi_stati","multiple_stati")

208

("already_reported",)

300

("multiple_choices",)

301

("moved_permanentiy","moved","\o-")

302

("found",)

303

("see_other","other")

304

("not_modified")

305

("use_proxy")

306

("switch_proxy")

307

("temporary_redirect","remporary_moved","temporary")

308

("permanent_redirect","resume_incomplete","resume")

400

("bad_request","bad")

401

("unauthorized",)

402

("payment_required","payment")

403

("forbidden",)

404

("not_found","-o-")

405

("method_not_allowed","not_allowed")

406

("not_acceptable",)

407

("proxy_authentication_required","proxy_auth","proxy_authentication")

408

("request_timeout","timeout")

409

("conflict",)

410

("gone",)

411

("length_required",)

412

("precondition_falled","precondition")

413

("request_entity_too_large",)

414

("request_uril_too_large",)

415

("unsupported_media_type","unsupported_media","media_type")

416

("requested_range_not_satisfiable"," requested_range"," range_not_satisfiable")

417

("expectation_failed",)

418

("im_a_teapot","teapot","i_am_a_teapot")

421

("misdirected_request",)

422

("unprocessable_entity","unprocessable")

423

("locked",)

424

("failed_dependency","dependency")

425

("unordered_collection","unordered")

426

("upgrade_required","upgrade")

428

("precondition_required","precondition")

429

("too_many_requests","too_mary")

431

("header_fields_too_large"," fields_too_large")

444

("no_response","none")

449

("retry_with","retry")

450

("unavallable_for_legal_reasons","parental_controls")

451

("unavallable_for_legal_reasons","legal_reasons")

499

("client_closed_request",)

500

("internal_server_error","server_error","/o\","×")

501

("not_implemented",)

502

("bad_gateway",)

503

("service_unavaliable","unavaliable")

504

("gateway_timeout")

505

("http_version_not_supported","http_version")

506

("variant_also_negotiates",)

507

("insufficient_storage",)

509

("bandwidth_limit_exceeded","bandwidth")

510

("not_extended",)

511

("network_authentication_required","network_auth","network_authentication")

request的高級操作

文件上傳

1 import requests
2 
3 files = {"file":open("test.png",'rb')}
4 
5 response = requests.post("http://httpbin.org/post",files=files)   #需要用post方法
6 
7 print(response.text)

text返回的files是一個(gè)文件字節(jié)流

獲取cookie

1 response = requests.get("http://www.baidu.com")
2 
3 print(response.cookies)
4 
5 for key,value in response.cookies.items():
6 
7 print(key + "=" + value)

會話維持:用來模擬登錄

1 requests.get("http://httpbin.org/cookies/set/number/1234")   #調(diào)用cookies的set方法設(shè)置cookies
2 
3 response = requests.get("http://httpbin.org/cookies")  #獲取cookies
4 
5 print(response.cookies)

這樣結(jié)果出來是空的,因?yàn)槟阏埱罅藘纱蝕et方法,等于是兩個(gè)瀏覽器各自請求

修改一下:

1 s = requests.Session()
2 
3 s.get("http://httpbin.org/cookies/set/number/1234")
4 
5 response = s.get("http://httpbin.org/cookies")
6 
7 print(response.text)

證書驗(yàn)證

#這個(gè)12306的證書是一個(gè)不安全的,直接請求會報(bào)錯(cuò):SSL error證書錯(cuò)誤
response = requests.get("http://www.12306.cn")
# 這樣改之后就返回200ok了,但是會有警告
 response = requests.get("http://www.12306.cn",verfiy=False)

再修改:

1 from requests.packages import urllib3
2 
3 urllib3.disable_warnings()
4 
5 response = requests.get("http://www.12306.cn",verfiy=False)
6 
7 print(response.text)

這樣就沒有警告了

代理設(shè)置

設(shè)置http或者h(yuǎn)ttps代理,并且沒有用戶名密碼的情況下:

 1 Import requests
 2 
 3 proxies = {
 4 
 5 "http":"http://127.0.0.1:9743/",
 6 
 7 "https":"https://127.0.0.1:9743/"
 8 
 9 }
10 
11 response = requests.get("https://www.taobao.com",proxies=proxies)
12 
13 print(response.status_code)

設(shè)置http或者h(yuǎn)ttps代理,有用戶名密碼

proxies = {

"http":" http://user:password@ 127.0.0.1:9743/"

}

response = requests.get("https://www.taobao.com",proxies=proxies)

print(response.status_code)

如果代理不是http或者h(yuǎn)ttps,是socks4或者socks5,則字典的鍵值還是http,但是值變了:

首先需要pip install "requests[socks]"

Import requests

proxies = {

"http":"socks5://127.0.0.1:9743/",

"https":"socks5://127.0.0.1:9743/"

}

response = requests.get("https://www.taobao.com",proxies=proxies)

print(response.status_code)

超時(shí)設(shè)置

import requests

response = requests.get("https://www.taobao.com",timeout=1)  #設(shè)置超過1秒就算超時(shí)

print(response.status_code)

超時(shí)以后會報(bào)一個(gè)異常:ReadTimeout

可以使用try捕獲異常,修改代碼為:

Import requests

from requests.exceptions import ReadTimeout

try:

  response = requests.get("https://www.taobao.com",timeout=1)  #設(shè)置超過1秒就算超時(shí)

  print(response.status_code)

except ReadTimeout:

    print("timeout")

認(rèn)證設(shè)置

有寫網(wǎng)址需要用戶名密碼登錄后才可以看到內(nèi)容,則:

import requests

from requests.auth import HTTPBasicAuth

r = requests.get("http://120.27.34.24:9001",auth=HTTPBasicAuth("user","123"))

print(r.status_code)

或者第二種寫法:

Import requests

 

r=requests.get("http://120.27.34.24:9001",auth= ("user","123"))

print(r.status_code)

異常處理

import requests

from requests.exceptions import ReadTimeout,HTTPError,ConnectionError,RequestException

try:
    response = requests.get("https://www.taobao.com",timeout=1)
    print(response.status_code)
except ReadTimeout:
    print("timeout")
except HTTPError:           #http異常
    print("http error")
except ConnectionError:       #網(wǎng)絡(luò)不好
    print("ConnectionError")
except RequestException:    #父類異常
    print("error")

總結(jié)

以上是生活随笔為你收集整理的python的requests用法详解的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。