标签:一个 flat sts height on() 应用 使用 分享 star
环境搭建好后,接下来我们先来了解一下requests的一些简单使用,主要包括:
本节首先来了解一下requests库中如何发送get请求:
一、看下方法定义:
1、到官方文档去了下requests.get()方法的定义,如下:
2、点击右上角的【source】,看一下它的源码如下:
看到最后一行return,get方法最后是通过调用 requests.request 方法实现的,其实在其它的请求方法如post,put,head,delete等方法都是调用的request方法,然后把请求方法的类型传递给request方法第一个参数。
3、HTTP协议是一个基于请求/响应模式的、无状态的,应用层协议。既然有请求,就有响应,来看下resquest中常用的响应信息:
二、get方法简单使用:
1、不带参数的get:
# -*- coding:utf-8 -*- #不带参数的get import requests import json host = "http://httpbin.org/" endpoint = "get" url = ‘‘.join([host,endpoint]) r = requests.get(url) #response = r.json() print type(r.text) print (eval(r.text))
输出:
{ ‘origin‘: ‘183.14.133.88‘, ‘headers‘: { ‘Connection‘: ‘close‘, ‘Host‘: ‘httpbin.org‘, ‘Accept-Encoding‘: ‘gzip, deflate‘, ‘Accept‘: ‘*/*‘, ‘User-Agent‘: ‘python-requests/2.18.1‘ }, ‘args‘: { }, ‘url‘: ‘http: //httpbin.org/get‘ }
# -*- coding:utf-8 -*- #带参数的get import requests import json host = "http://httpbin.org/" endpoint = "get" url = ‘‘.join([host,endpoint]) params = {"show_env":"1"} r = requests.get(url=url,params=params) print r.url
输出:
http://httpbin.org/get?show_env=1 { ‘origin‘: ‘183.14.133.88‘, ‘headers‘: { ‘X-Request-Id‘: ‘ebe922b4-c463-4fe9-9faf-49748d682fd7‘, ‘Accept-Encoding‘: ‘gzip, deflate‘, ‘X-Forwarded-Port‘: ‘80‘, ‘Total-Route-Time‘: ‘0‘, ‘Connection‘: ‘close‘, ‘Connect-Time‘: ‘0‘, ‘Via‘: ‘1.1vegur‘, ‘X-Forwarded-For‘: ‘183.14.133.88‘, ‘Accept‘: ‘*/*‘, ‘User-Agent‘: ‘python-requests/2.18.1‘, ‘X-Request-Start‘: ‘1504755961007‘, ‘Host‘: ‘httpbin.org‘, ‘X-Forwarded-Proto‘: ‘http‘ }, ‘args‘: { ‘show_env‘: ‘1‘ }, ‘url‘: ‘http: //httpbin.org/get?show_env=1‘ }
3、带header的get:
# -*- coding:utf-8 -*- import requests import json host = "http://httpbin.org/" endpoint = "get" url = ‘‘.join([host,endpoint]) headers = {"User-Agent":"test request headers"} r = requests.get(url) r = requests.get(url,headers=headers) #response = r.json() print (eval(r.text))[‘headers‘][‘User-Agent‘]
输出:
test request headers
4、同时带参数和header:
# -*- coding:utf-8 -*- import requests import json host = "http://httpbin.org/" endpoint = "get" url = ‘‘.join([host,endpoint]) headers = {"User-Agent":"test request headers"} params = {"show_env":"1"} r = requests.get(url) r = requests.get(url,headers=headers,params=params) #response = r.json() print (eval(r.text))[‘headers‘][‘User-Agent‘] print r.url
输出:
test request headers http://httpbin.org/get?show_env=1
python接口自动化测试(二)-requests.get()
标签:一个 flat sts height on() 应用 使用 分享 star
原文地址:http://www.cnblogs.com/ruanchengqing/p/7560320.html