Requests模块

1、模块说明

  Requests 是使用 Apache2 Licensed 许可证的 HTTP 库。用 Python 编写,真正的为人类着想。

  Python 标准库中的 urllib2 模块提供了你所需要的大多数 HTTP 功能,但是它的 API 太渣了。它是为另一个时代、另一个互联网所创建的。它需要巨量的工作,甚至包括各种方法覆盖,来完成最简单的任务。

  在Python的世界里,事情不应该这么麻烦。

  Requests 使用的是 urllib3,因此继承了它的所有特性。Requests 支持 HTTP 连接保持和连接池,支持使用 cookie 保持会话,支持文件上传,支持自动确定响应内容的编码,支持国际化的 URL 和 POST 数据自动编码。现代、国际化、人性化。

(以上转自Requests官方文档)

2、模块安装

pip install requests

尝试在IDE中import requests,如果没有报错,那么安装成功。

3、所有请求类型

#HTTP请求类型
#get类型
r = requests.get('http://127.0.0.1:8000/timeline.json')
#post类型
r = requests.post("http://127.0.0.1:8000/post")
#put类型
r = requests.put("http://127.0.0.1:8000/put")
#delete类型
r = requests.delete("http://127.0.0.1:8000/delete")
#head类型
r = requests.head("http://127.0.0.1:8000/head")
#options类型
r = requests.options("http://127.0.0.1:8000/get")

  

4、Get请求

注:get请求中只包含请求头信息,没有请求体

from django.views import View

class Index(View):

    def get(self, request):

        auth_key = request.META.get('HTTP_AUTH_KEY')
print(auth_key)
return HttpResponse('requests模块测试') # HTTP_AUTH_KEY'(76981496) = {str}'' web端.py

web端.py

发送请求:

import requests

response = requests.get('http://127.0.0.1:8000/index/') #发送get请求

print(response.text)        #字符串类型
print(response.content) #bytes类型 # requests模块测试
# b'requests\xe6\xa8\xa1\xe5\x9d\x97\xe6\xb5\x8b\xe8\xaf\x95'

传递参数:

import requests
payload = {'keyword': '299095cc', 'salecityid': '2'}
response = requests.get('http://127.0.0.1:8000/index/',params=payload) # 发送get请求,等同于下面访问路径 print(response.url) # 打印请求路径 # http://127.0.0.1:8000/index/?salecityid=2&keyword=299095cc

传递请求头:

import requests
auth_key = "299095cc"
response = requests.get('http://127.0.0.1:8000/index/',
headers={'auth-key':auth_key}) # headers里的key值不能包含_

添加浏览器类型:

#定制请求头
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

网页编码:

#获取/修改网页编码
r = requests.get('https://github.com/timeline.json')
print r.encoding
r.encoding = 'utf-8'

json数据转换: 

#json处理
r = requests.get('https://github.com/timeline.json')
print r.json() #需要先import json

状态响应: 

#响应状态码
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') #访问响应头部分内容的两种方式

获取和携带cookie:

# 获取
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=(5,1)) # 前面是连接时间,后面是数据传送时间

访问代理:

#设置访问代理
proxies = {
"http": "http://10.10.10.10:8888",
"https": "http://10.10.10.100:4444",
}
r = requests.get('http://m.ctrip.com', proxies=proxies)

存储图片:

import requests
from bs4 import BeautifulSoup r = requests.get("http://www.pythonscraping.com")
bs = BeautifulSoup(r.text,'html.parser')
image = bs.find("a", {"id": "logo"}).find("img")["src"] ir = requests.get(image)
if ir.status_code == 200:
open('logo.jpg', 'wb').write(ir.content)

 

5、Post请求

注:post请求包含请求头,请求体,下面只写get中不存在的参数

用户认证:

# 认证,form表单的提交
url = 'http://m.ctrip.com'
data= {'username': 'lzl','password':'123456'}
r = requests.post(url, data=data) #复杂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)

  

 6、中文乱码

reptext = response.content.decode('gbk')

 

7、发送https请求

import json
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
url = 'https://192.168.1.12:8038/v1/call/DailbackCallBack_XL.ashx?action=NoticeCall_XL_176_KeyPress&spid=176'
data = {'requestid': u'2017110000000127', 'clid': u'057128214997', 'stime': '2017-11-22 14:53:17',
'ctime': '2017-11-22 14:52:57', 'accountno': u'800100', 'keypress': u'123', 'phonenum': u'18515142614',
'etime': '2017-11-22 14:53:23', 'recording': '', 'sn': u'54587192661872',
'result': 0}
response = requests.post(url=url,data=json.dumps(data),verify=False)
print(response.text)

  

 

Python开发【模块】:Requests(一)的更多相关文章

  1. Python第三方模块--requests简单使用

    1.requests简介 requests是什么?python语言编写的,基于urllib的第三方模块 与urllib有什么关系?urllib是python的内置模块,比urllib更加简洁和方便使用 ...

  2. python开发模块基础:re正则

    一,re模块的用法 #findall #直接返回一个列表 #正常的正则表达式 #但是只会把分组里的显示出来#search #返回一个对象 .group()#match #返回一个对象 .group() ...

  3. python开发模块基础:异常处理&hashlib&logging&configparser

    一,异常处理 # 异常处理代码 try: f = open('file', 'w') except ValueError: print('请输入一个数字') except Exception as e ...

  4. python开发模块基础:os&sys

    一,os模块 os模块是与操作系统交互的一个接口 #!/usr/bin/env python #_*_coding:utf-8_*_ ''' os.walk() 显示目录下所有文件和子目录以元祖的形式 ...

  5. python开发模块基础:序列化模块json,pickle,shelve

    一,为什么要序列化 # 将原本的字典.列表等内容转换成一个字符串的过程就叫做序列化'''比如,我们在python代码中计算的一个数据需要给另外一段程序使用,那我们怎么给?现在我们能想到的方法就是存在文 ...

  6. python开发模块基础:time&random

    一,time模块 和时间有关系的我们就要用到时间模块.在使用模块之前,应该首先导入这个模块 常用方法1.(线程)推迟指定的时间运行.单位为秒. time.sleep(1) #括号内为整数 2.获取当前 ...

  7. python开发模块基础:collections模块&paramiko模块

    一,collections模块 在内置数据类型(dict.list.set.tuple)的基础上,collections模块还提供了几个额外的数据类型:Counter.deque.defaultdic ...

  8. python开发模块基础:正则表达式

    一,正则表达式 1.字符组:[0-9][a-z][A-Z] 在同一个位置可能出现的各种字符组成了一个字符组,在正则表达式中用[]表示字符分为很多类,比如数字.字母.标点等等.假如你现在要求一个位置&q ...

  9. Python开发——目录

    Python基础 Python开发——解释器安装 Python开发——基础 Python开发——变量 Python开发——[选择]语句 Python开发——[循环]语句 Python开发——数据类型[ ...

  10. Python开发【第六篇】:模块

    模块,用一砣代码实现了某个功能的代码集合. 类似于函数式编程和面向过程编程,函数式编程则完成一个功能,其他代码用来调用即可,提供了代码的重用性和代码间的耦合.而对于一个复杂的功能来,可能需要多个函数才 ...

随机推荐

  1. 微信绑定用户服务端代码-根据code获取openId然后绑定用户

    目录结构: isa.qa.core.weixin.message.resp包和isa.qa.core.weixin.util包中为微信绑定的工具类,就不一一贴出代码,详见附件,下载地址: http:/ ...

  2. 【mysql】恢复备份

    windows环境: 打开cmd cd 到备份数据目录 mysql -u*** -p use database; source *****.sql;

  3. 第六章 mybatis注入映射器

    为了代替手工使用 SqlSessionDaoSupport 或 SqlSessionTemplate 编写数据访问对象 (DAO)的代码,MyBatis-Spring 提供了一个动态代理的实现:Map ...

  4. .Net中的序列化和反序列化详解

    序列化通俗地讲就是将一个对象转换成一个字节流的过程,这样就可以轻松保存在磁盘文件或数据库中.反序列化是序列化的逆过程,就是将一个字节流转换回原来的对象的过程. 然而为什么需要序列化和反序列化这样的机制 ...

  5. C#委托和事件详解

    委托Delegate delegate是C#中的一种类型,它实际上是一个能够持有对某个方法的引用的类.与其它的类不同,delegate类能够拥有一个签名(signature),并且它"只能持 ...

  6. JQuery上传插件Uploadify使用详解 asp.net版

    先来一个实例 Uploadify插件是JQuery的一个文件支持多文件上传的上传插件,ajax异步上传,实现的效果非常不错,带进度显示.不过官方提供的实例时php版本的,本文将详细介绍Uploadif ...

  7. python--dict和set类型--4

    原创博文,转载请标明出处--周学伟http://www.cnblogs.com/zxouxuewei/ 一.什么是dict 我们已经知道,list 和 tuple 可以用来表示顺序集合,例如,班里同学 ...

  8. ionic ui框架及creator使用帮助

    UI框架使用方法:http://ionicframework.com/docs/api/ PS:路由之类的其他js代码示例建议用 官方的app 生成器弄一个简单的页面,然后下载回来看 https:// ...

  9. Spring装配Bean的过程补充

    对上一篇的<Spring装配Bean的过程>的过程说一下,不然真产生了误区. 误区在哪里呢?那就是spring bean的作用域问题. 说哈常用的两种作用域:默认是scope = sing ...

  10. docker tag 详解

    docker tag 用于给镜像打标签,语法如下: docker tag SOURCE_IMAGE[:TAG] TARGET_IMAGE[:TAG] ① 比如我现在有一个 centos 镜像: [ro ...