一、requests模塊說明
介紹:
Requests是Python語言的第三方的庫,專門用於發送HTTP請求。在Python語言中,雖然提供了urllib2和urllib的庫,但是相比較而言,Requests仍然是實現接口測試最好的選擇,因為它是用起來更加簡便。
特點:
1.Requests支持HTTP連接保持和連接池,支持使用cookie保持會話,支持文件上傳,支持自動響應內容的編碼,支持國際化的URL和POST數據自動編碼。
2.在python內置模塊的基礎上進行了高度的封裝,從而使得python進行網絡請求時,變得人性化,使用Requests可以輕而易舉的完成瀏覽器可有的任何操作。
3.Requests會自動實現持久連接keep-alive,現代,國際化,友好。
二、安裝並導入模塊安裝requests
-
Pycharm在線安裝:
File-Settings-Project Interpreter

-
pip在線安裝 :
cmd-> pip install requests

-
國內源:
pip install requests -i
https://pypi.tuna.tsinghua.edu.cn/simple/

導入requests
import requests
三、requests模塊發送get請求
基本介紹
語法格式:requests.get(url, params=None, **kwargs)
如:requests.get(url=url, headers=headers, params=params)
-
url:請求url地址
-
headers:請求頭
-
params:參數
簡單使用
-
獲取響應狀態碼: res.status_code
-
獲取響應消息: res.content
-
獲取請求頭: res.request.headers
-
獲取響應頭: res.headers
-
獲取響應數據 res.text
響應結果一般有三種格式:html、json、text;
-
獲取cookie res.cookies
cookie是一種類字典的數據格式,若想打印字典的值,可以根據key;
-
res.json():如果返回結果是json格式,可以把響應結果利用json()來進行解析;
示例:
# !/usr/bin/python3# -*- coding:utf-8 -*-# @Time:2020/1/26 07:00# @微信公眾號:ITester軟件測試小棧# @Author:coco# @Python交流群:604469740# @Email:3593721069@qq.com# @File:test.py# @Software:PyCharm#請求urlurl = "http://httpbin.org/get"#請求頭headers= {"Accept": "*/*","Accept-Encoding": "gzip, deflate","User-Agent": "python-requests/2.9.1"}#查詢字符串params = {'name': 'coco', 'age': '18'}res= requests.get(url, headers=headers, data=params)#獲取響應狀態碼 res.status_codeprint("響應狀態碼:", res.status_code)# 獲取響應消息 res.contentprint("響應消息:", res.content)# 獲取請求頭 res.request.headersprint("請求頭:", res.request.headers)# 獲取響應頭 res.headersprint("響應頭:", res.headers)# 獲取響應數據 res.textprint("響應數據:", res.text)#獲取cookie res.cookiesprint("cookie:", res.cookies)# res.json()print("json:", res.json())
執行結果:

更多系列文章,可以關注微信公眾號:ITester軟件測試小棧

