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开发【第六篇】:模块
模块,用一砣代码实现了某个功能的代码集合. 类似于函数式编程和面向过程编程,函数式编程则完成一个功能,其他代码用来调用即可,提供了代码的重用性和代码间的耦合.而对于一个复杂的功能来,可能需要多个函数才 ...
随机推荐
- CentOS7设置开机自启动命令大全
任务 旧指令 新指令 使某服务自动启动 chkconfig --level 3 httpd on systemctl enable httpd.service 使某服务不自 ...
- asp.net mvc中用angularJs写的增删改查的demo。初学者,求指点。。
直接给个代码下载链接.... http://pan.baidu.com/s/1FfVgq 本人刚刚学习angularJs,感觉双向数据绑定蛮爽的... 之前的代码存在点问题,已修复
- 让UIButton在按下时没有高亮效果
How are you setting the images for the different UIControlStates on the button? Are you setting a ba ...
- why pure virtual function has definition 为什么可以在基类中实现纯虚函数
看了会音频,无意搜到一个frameworks/base/include/utils/Flattenable.h : virtual ~Flattenable() = 0; 所以查了下“纯虚函数定义实现 ...
- 左连接去重(objec)
需求场景: 1.前端使用的object-table(angularJs) 2.自定义模糊查询 可以模糊查询主表,主表没有数据的时候,可通过字表的(name或者hostname)字段来查询(主-子:一对 ...
- ubuntu 16.04 appstreamcli 问题
http://blog.csdn.net/zhbpd/article/details/77508675
- CSS3 transform 引起z-index失效
https://my.oschina.net/u/2941696/blog/1529373
- QQ第三方登录实例demo(QQSDK包优化)
实现效果: 实现流程: 1.注冊QQ互联开发人员 QQ互联官网 注冊成为开发人员(须要审核) 2.审核通过之后 申请应用(须要互联人员审核*须要备案成功的线上域名) 以下我们開始下载QQsdk包 QQ ...
- Effective C++ Item 15 Provide access to raw resources in resource-managing classes
In last two item, I talk about resource-managing using RAII, now comes to the practical part. Often, ...
- 如何把he_llo wo_rld 变成 HeLlo WoRld
有人问如何把he_llo wo_rld 变成 HeLlo WoRld,估计应该是一道面试的基础题吧. 思路很多种,就看如何实现 思路一.先根据空格分隔,然后转大写,最后再拼接.代码如下 <?ph ...