HTTP request python官方文档:http://cn.python-requests.org/zh_CN/latest/

1.  环境

基于环境,需要安装requests 模块,安装方法 pip install requests
想学习requests,就通过help吧

import requests
help(requests)

返回结果如下:

C:\Python27\python.exe E:/test/interface/g_3.py
Help on package requests: NAME
requests FILE
c:\python27\lib\site-packages\requests\__init__.py DESCRIPTION
Requests HTTP Library
~~~~~~~~~~~~~~~~~~~~~ Requests is an HTTP library, written in Python, for human beings. Basic GET
usage: >>> import requests
>>> r = requests.get('https://www.python.org')
>>> r.status_code
200
>>> 'Python is a programming language' in r.content
True ... or POST: >>> payload = dict(key1='value1', key2='value2')
>>> r = requests.post('http://httpbin.org/post', data=payload)
>>> print(r.text)
{
...
"form": {
"key2": "value2",
"key1": "value1"
},
...
} The other HTTP methods are supported - see `requests.api`. Full documentation
is at <http://python-requests.org>. :copyright: (c) 2017 by Kenneth Reitz.
:license: Apache 2.0, see LICENSE for more details. PACKAGE CONTENTS
__version__
_internal_utils
adapters
api
auth
certs
compat
cookies
exceptions
help
hooks
models
packages
sessions
status_codes
structures
utils FUNCTIONS
check_compatibility(urllib3_version, chardet_version) DATA
__author__ = 'Kenneth Reitz'
__author_email__ = 'me@kennethreitz.org'
__build__ = 137220
__cake__ = u'\u2728 \U0001f370 \u2728'
__copyright__ = 'Copyright 2017 Kenneth Reitz'
__description__ = 'Python HTTP for Humans.'
__license__ = 'Apache 2.0'
__title__ = 'requests'
__url__ = 'http://python-requests.org'
__version__ = '2.18.4'
codes = <lookup 'status_codes'> VERSION
2.18.4 AUTHOR
Kenneth Reitz Process finished with exit code 0

获取requests所有的方法和类,就使用dir吧

import requests
print dir(requests)

返回如下:

['ConnectTimeout', 'ConnectionError', 'DependencyWarning', 'FileModeWarning', 'HTTPError', 'NullHandler', 'PreparedRequest', 'ReadTimeout', 'Request', 'RequestException', 'RequestsDependencyWarning', 'Response', 'Session', 'Timeout', 'TooManyRedirects', 'URLRequired', '__author__', '__author_email__', '__build__', '__builtins__', '__cake__', '__copyright__', '__description__', '__doc__', '__file__', '__license__', '__name__', '__package__', '__path__', '__title__', '__url__', '__version__', '_internal_utils', 'adapters', 'api', 'auth', 'certs', 'chardet', 'check_compatibility', 'codes', 'compat', 'cookies', 'delete', 'exceptions', 'get', 'head', 'hooks', 'logging', 'models', 'options', 'packages', 'patch', 'post', 'put', 'request', 'session', 'sessions', 'status_codes', 'structures', 'urllib3', 'utils', 'warnings']

2.  HTTP协议:

根据 HTTP 标准, HTTP 请求可以使用多种请求方法。
HTTP1.0 定义了三种请求方法: GET, POST 和 HEAD 方法。

HTTP1.1 新增了五种请求方法: 共GET, POST, HEAD, OPTIONS, PUT, DELETE, TRACE 和 CONNECT 方法

3.  requests模块入门:

#HTTP请求类型
#get类型
r = requests.get('https://github.com/timeline.json')
#post类型
r = requests.post("http://m.ctrip.com/post")
#put类型
r = requests.put("http://m.ctrip.com/put")
#delete类型
r = requests.delete("http://m.ctrip.com/delete")
#head类型
r = requests.head("http://m.ctrip.com/head")
#options类型
r = requests.options("http://m.ctrip.com/get") #获取响应内容
print r.content #以字节的方式去显示,中文显示为字符
print r.text #以文本的方式去显示 #URL传递参数
payload = {'keyword': '日本', 'salecityid': ''}
r = requests.get("http://m.ctrip.com/webapp/tourvisa/visa_list", params=payload)
print r.url #示例为http://m.ctrip.com/webapp/tourvisa/visa_list?salecityid=2&keyword=日本 #获取/修改网页编码
r = requests.get('https://github.com/timeline.json')
print r.encoding
r.encoding = 'utf-8' #json处理
r = requests.get('https://github.com/timeline.json')
print r.json() #需要先import json #定制请求头
url = 'http://m.ctrip.com'
headers = {'User-Agent' : 'Mozilla/5.0 (Linux; Android 4.2.1; en-us; Nexus 4 Build/JOP40D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19'}
r = requests.post(url, headers=headers)
print r.request.headers #复杂post请求
url = 'http://m.ctrip.com'
payload = {'some': 'data'}
r = requests.post(url, data=json.dumps(payload)) #如果传递的payload是string而不是dict,需要先调用dumps方法格式化一下 #post多部分编码文件
url = 'http://m.ctrip.com'
files = {'file': open('report.xls', 'rb')}
r = requests.post(url, files=files) #响应状态码
r = requests.get('http://m.ctrip.com')
print r.status_code #响应头
r = requests.get('http://m.ctrip.com')
print r.headers
print r.headers['Content-Type']
print r.headers.get('content-type') #访问响应头部分内容的两种方式 #Cookies
url = 'http://example.com/some/cookie/setting/url'
r = requests.get(url)
r.cookies['example_cookie_name'] #读取cookies url = 'http://m.ctrip.com/cookies'
cookies = dict(cookies_are='working')
r = requests.get(url, cookies=cookies) #发送cookies #设置超时时间
r = requests.get('http://m.ctrip.com', timeout=0.001) #设置访问代理
proxies = {
"http": "http://10.10.10.10:8888",
"https": "http://10.10.10.100:4444",
}
r = requests.get('http://m.ctrip.com', proxies=proxies)

4、Requests示例

json请求

#!/user/bin/env python
#coding=utf-8
import requests
import json class url_request():
def __init__(self):
""" init """ if __name__=='__main__':
headers = {'Content-Type' : 'application/json'}
payload = {'CountryName':'中国',
'ProvinceName':'陕西省',
'L1CityName':'汉中',
'L2CityName':'城固',
'TownName':'',
'Longitude':'107.33393',
'Latitude':'33.157131',
'Language':'CN'
}
r = requests.post("http://www.xxxxxx.com/CityLocation/json/LBSLocateCity",headers=headers,data=payload)
#r.encoding = 'utf-8'
data=r.json()
if r.status_code!=200:
print "LBSLocateCity API Error " + str(r.status_code)
print data['CityEntities'][0]['CityID'] #打印返回json中的某个key的value
print data['ResponseStatus']['Ack']
print json.dumps(data,indent=4,sort_keys=True,ensure_ascii=False) #树形打印json,ensure_ascii必须设为False否则中文会显示为unicode

xml请求

#!/user/bin/env python
#coding=utf-8
import requests class url_request():
def __init__(self):
""" init """ if __name__=='__main__': headers = {'Content-type': 'text/xml'}
XML = '<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><Request xmlns="http://tempuri.org/"><jme><JobClassFullName>WeChatJSTicket.JobWS.Job.JobRefreshTicket,WeChatJSTicket.JobWS</JobClassFullName><Action>RUN</Action><Param>1</Param><HostIP>127.0.0.1</HostIP><JobInfo>1</JobInfo><NeedParallel>false</NeedParallel></jme></Request></soap:Body></soap:Envelope>'
url = 'http://jobws.push.mobile.xxxxxxxx.com/RefreshWeiXInTokenJob/RefreshService.asmx'
r = requests.post(url,headers=headers,data=XML)
#r.encoding = 'utf-8'
data = r.text
print data

接口_requests_基于python的更多相关文章

  1. 简单实现接口自动化测试(基于python+unittest)

    简单实现接口自动化测试(基于python+unittest) 简介 本文通过从Postman获取基本的接口测试Code简单的接口测试入手,一步步调整优化接口调用,以及增加基本的结果判断,讲解Pytho ...

  2. 接口自动化 基于python+Testlink+Jenkins实现的接口自动化测试框架[V2.0改进版]

    基于python+Testlink+Jenkins实现的接口自动化测试框架[V2.0改进版]   by:授客 QQ:1033553122 由于篇幅问题,,暂且采用网盘分享的形式: 下载地址: [授客] ...

  3. 接口自动化 基于python实现的http+json协议接口自动化测试框架源码(实用改进版)

    基于python实现的http+json协议接口自动化测试框架(实用改进版)   by:授客 QQ:1033553122 欢迎加入软件性能测试交流QQ群:7156436     目录 1.      ...

  4. 接口自动化- 基于 Python

    准备工作 这部分其实在谷歌或者百度上搜索下就可以完成的,可是我就是想再啰嗦一遍,说不定有比我更懒的同学呢哈哈~ 第一步 Python的安装配置 打开官网: https://www.python.org ...

  5. 接口自动化 基于python+Testlink+Jenkins实现的接口自动化测试框架

    链接:http://blog.sina.com.cn/s/blog_13cc013b50102w94u.html

  6. 接口自动化 [授客]基于python+Testlink+Jenkins实现的接口自动化测试框架V3.0

    基于python+Testlink+Jenkins实现的接口自动化测试框架V3.0   by:授客 QQ:1033553122     博客:http://blog.sina.com.cn/ishou ...

  7. 如何简单实现接口自动化测试(基于 python) 原博主地址https://blog.csdn.net/gitchat/article/details/77849725

    如何简单实现接口自动化测试(基于 python) 2017年09月05日 11:52:25 阅读数:9904 GitChat 作者:饿了么技术社区 原文:如何简单实现接口自动化测试(基于 python ...

  8. 基于python+Testlink+Jenkins实现的接口自动化测试框架V3.0

    基于python+Testlink+Jenkins实现的接口自动化测试框架V3.0 目录 1. 开发环境2. 主要功能逻辑介绍3. 框架功能简介 4. 数据库的创建 5. 框架模块详细介绍6. Tes ...

  9. Python 基于python实现的http接口自动化测试框架(含源码)

    基于python实现的http+json协议接口自动化测试框架(含源码) by:授客 QQ:1033553122      欢迎加入软件性能测试交流 QQ群:7156436  由于篇幅问题,采用百度网 ...

随机推荐

  1. js中数组的api整理

    首先列出所有的方法: join(), sort(), slice(), splice(), concat(), reverse(), push()+pop(), shift()+unshift(), ...

  2. 『ACM C++』 PTA 天梯赛练习集L1 | 040-41

    近期安排 校赛3.23天梯赛3.30华工校赛 4.21省赛 5.12 ------------------------------------------------L1-040----------- ...

  3. laravel 5.7 resources 本地化 简体中文

    使用方法: 新建目录[项目目录/resources/lang/zh] 按以下内容创建文件,并将内容复制到文件中 修改 config/app.php 'locale' => 'zh', 'fall ...

  4. c和c++单链表

    c++版 #include<iostream> #include<malloc.h> using namespace std; struct node{ int data; n ...

  5. 阿里云centOS7.4上MySql5.6安装

    最近一个项目要部署在阿里云上,为了开发团队方便,我自费买了个ECS,先装个数据库给开发用. 因为之前都是在真机安装,与这次阿里云上的部署比起来,还是有点区别的. Mysql 1 安装mysql版本包 ...

  6. Redis服务端和客户端的命令

    服务器端 服务器端的命令为redis-server 可以使⽤help查看帮助⽂档 redis-server --help 个人习惯 ps aux | grep redis 查看redis服务器进程su ...

  7. php bug 调试助手 debug_print_backtrace()

    debug_print_backtrace() 是一个很低调的函数,很少有人注意过它. 不过当我对着一个对象调用另一个对象再调用其它的对象和文件中的一个函数出错时,它也许正在一边笑呢 如果我们想知道某 ...

  8. C 二维数组,以及自定义二维数组

    C 二维数组,以及自定义二维数组 我们通常情况下是这样定义一个二维数组的: int a[10][15]; 我们分别查看一下a,a[0],*a 都是一样的值吧 我们可以这么理解: a是一个数组的数组 a ...

  9. c语言程序设计:用strcpy比较数组(银行卡密码程序设计),strcpy(复制数组内容)和getchar()(敲键盘字符,统计不想要的字符的个数)

    统计从键盘输入一行字符的个数: 1 //用了getchar() 语句 2 //这里的\n表示回车 #include <stdio.h> #include <stdlib.h> ...

  10. 优步北京B组奖励政策

    用户组:优步北京B组(2015年7月20日前激活的部分司机) 更新日期:2015年8月4日 滴滴快车单单2.5倍,注册地址:http://www.udache.com/ 如何注册Uber司机(全国版最 ...