Python requests模块使用指南:安装与基础用法
本文介绍Python中广泛使用的HTTP库requests。它基于Apache2许可证,旨在提供比标准库urllib2更简洁、人性化的API。文章涵盖通过pip或easy_install安装requests的方法,并演示了GET、POST等常见HTTP请求类型、参数传递、响应处理、编码设置及代理配置等核心功能,帮助开发者快速上手网络请求开发。
Requests模块概述
Requests是一个遵循Apache2许可证的HTTP客户端库,由Python编写,设计理念是真正从用户角度出发,力求简洁易用。
虽然Python标准库中的urllib2模块提供了大部分HTTP功能,但其API设计较为粗糙,仿佛是为过去的互联网时代打造的。它要求开发者进行大量繁琐的工作,甚至需要覆盖各种复杂方法,才能完成最简单的HTTP任务。
在Python生态中,网络请求操作不应如此复杂。
Requests底层基于urllib3构建,因此继承了其所有特性。它支持HTTP连接保持和连接池管理,允许通过Cookie维持会话状态,支持文件上传功能,并能自动识别响应内容的编码格式。此外,它还支持国际化URL处理以及POST数据的自动编码,体现了现代、国际化且人性化的设计特点。
Requests模块安装
点击下载链接获取资源
随后执行安装程序
$ python setup.py install
个人推荐使用pip进行安装
pip install requests
也可以采用easy_install方式进行安装
easy_install requests
尝试在集成开发环境(IDE)中导入requests模块,若未出现报错信息,则表明安装成功。
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': '2'}
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)
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
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









