Python开发【模块】:Requests(一)
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(一)的更多相关文章
- Python第三方模块--requests简单使用
1.requests简介 requests是什么?python语言编写的,基于urllib的第三方模块 与urllib有什么关系?urllib是python的内置模块,比urllib更加简洁和方便使用 ...
- python开发模块基础:re正则
一,re模块的用法 #findall #直接返回一个列表 #正常的正则表达式 #但是只会把分组里的显示出来#search #返回一个对象 .group()#match #返回一个对象 .group() ...
- python开发模块基础:异常处理&hashlib&logging&configparser
一,异常处理 # 异常处理代码 try: f = open('file', 'w') except ValueError: print('请输入一个数字') except Exception as e ...
- python开发模块基础:os&sys
一,os模块 os模块是与操作系统交互的一个接口 #!/usr/bin/env python #_*_coding:utf-8_*_ ''' os.walk() 显示目录下所有文件和子目录以元祖的形式 ...
- python开发模块基础:序列化模块json,pickle,shelve
一,为什么要序列化 # 将原本的字典.列表等内容转换成一个字符串的过程就叫做序列化'''比如,我们在python代码中计算的一个数据需要给另外一段程序使用,那我们怎么给?现在我们能想到的方法就是存在文 ...
- python开发模块基础:time&random
一,time模块 和时间有关系的我们就要用到时间模块.在使用模块之前,应该首先导入这个模块 常用方法1.(线程)推迟指定的时间运行.单位为秒. time.sleep(1) #括号内为整数 2.获取当前 ...
- python开发模块基础:collections模块¶miko模块
一,collections模块 在内置数据类型(dict.list.set.tuple)的基础上,collections模块还提供了几个额外的数据类型:Counter.deque.defaultdic ...
- python开发模块基础:正则表达式
一,正则表达式 1.字符组:[0-9][a-z][A-Z] 在同一个位置可能出现的各种字符组成了一个字符组,在正则表达式中用[]表示字符分为很多类,比如数字.字母.标点等等.假如你现在要求一个位置&q ...
- Python开发——目录
Python基础 Python开发——解释器安装 Python开发——基础 Python开发——变量 Python开发——[选择]语句 Python开发——[循环]语句 Python开发——数据类型[ ...
- Python开发【第六篇】:模块
模块,用一砣代码实现了某个功能的代码集合. 类似于函数式编程和面向过程编程,函数式编程则完成一个功能,其他代码用来调用即可,提供了代码的重用性和代码间的耦合.而对于一个复杂的功能来,可能需要多个函数才 ...
随机推荐
- 修改查看MYSQL字符集(charset)
From: http://www.cnblogs.com/fengqingtao/archive/2010/11/23/1885220.html 查看mysql的字符集 mysql> show ...
- ZOJ 3436 July Number(DFS)
题意 把一个数替换为这个数相邻数字差组成的数 知道这个数仅仅剩一位数 若最后的一位数是7 则称原来的数为 July Number 给你一个区间 求这个区间中July Number的个数 ...
- kafka学习之-配置详解
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreement ...
- win7笔记本电脑怎么做wifi热点
win7设置wifi热点后非常方便,可以给其他笔记本和手机之类支持无线上网的移动设备使用,接下来请看超简单的详细设置方法. 方法/步骤 1 第一步先打开“控制面板” 2 点击“网络和Internet” ...
- swift - UIAlertController 的用法
ios 8 以后苹果官方建议使用UIAlertController这个类,所以专门去网上找资料,了解了下用法, 1.创建一个alertController let alertController = ...
- Exception in thread "main" java.lang.NoSuchMethodError: org.testng.TestNG.configure(Lorg/testng/CommandLineArgs;)V
TestNG运行时报以下错误: Exception in thread "main" java.lang.NoSuchMethodError: org.testng.TestNG. ...
- jdk版本不一致问题
Exception in thread "main" java.lang.UnsupportedClassVersionError: cn/com/TestApp : Unsupp ...
- Unity 的OCulus VR开发遇到的坑---OC版本差异
我作为Unity新人,没有用过Unity5之前的任何版本,不熟悉任何操作.所以,就根据官方推荐,使用了5.1.1版本,然后根据官方版本对应推荐,果断选择下载了PC端的OC的0.6.0.1版本,对应的U ...
- Android 程序员必须知道的 53 个知识点
1. android 单实例运行方法 我们都知道 Android 平台没有任务管理器,而内部 App 维护者一个 Activity history stack 来实现窗口显示和销毁,对于常规从快捷方式 ...
- memset和memcpy函数、atoi函数
memset void *memset(void *s,int c,size_t n) 总的作用:将已开辟内存空间 s 的首 n 个字节的值设为值 c.如下: // 1.将已开辟内存空间s的首n个字节 ...