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. 扫盲:java中关于路径的问题

    ../FileName:当前工程的上级目录. ./FileName:当前工程所在的目录. /FileName:当前工程所在磁盘的根目录(windows下). FileName:当前工程所在的目录.

  2. win7cmd静态绑定arp

    netsh -c "172.16.3.1" "f4-ea-67-8b-91-cc"

  3. Spring定时器Quartz的用法

    首先导入需要的两个jar: spring-context-support-4.1.1.RELEASE.jar quartz-2.2.1.jar 1.创建两个类: 2. QuartzConfigurat ...

  4. 学习 TList 类的实现[2]

    我原来以为 TList 可能是一个链表, 其实只是一个数组而已. 你知道它包含着多大一个数组吗? MaxListSize 个!MaxListSize 是 Delphi 在 Classes 单元定义的一 ...

  5. Ubuntu 12.04.3 X64 使用 NFS 作为文件共享存储方式 安装 Oracle11g RAC

    nfs-server 在 Ubuntu上可以选择 : nfs-kernel-server:如果在windows上,可以选择:haneWIN NFS Server nfs-client Ubuntu上使 ...

  6. 用 webpack 构建 node 后端代码,使其支持 js 新特性并实现热重载

    https://zhuanlan.zhihu.com/p/20782320?utm_source=tuicool&utm_medium=referral

  7. XML高速入门

    XML是什么 Extensible Markup Language 自己定义标签: 用来数据传输: 可扩展标记语言,是一种类似超文本标记语言的标记语言. 与HTML的比較: 1.不是用来替代HTML的 ...

  8. day10<面向对象+>

    面向对象(package关键字的概述及作用) 面向对象(包的定义及注意事项) 面向对象(带包的类编译和运行) 面向对象(不同包下类之间的访问) 面向对象(import关键字的概述和使用) 面向对象(四 ...

  9. VirtualBox设置NAT端口映射

    原文地址 :http://www.2cto.com/os/201209/153863.html   VirtualBox设置NAT端口映射   好吧,我知道这个问题有很多人都讲过,但是,你们不觉得VB ...

  10. window 后台执行 redis(隐藏窗口)

    方法是在知乎上看的,链接:https://www.zhihu.com/question/22771030 实现方法是利用一个vbe脚本去运行一个bat脚本,在bat脚本里启动exe软件 PS:要想启动 ...