Python requests模块学习笔记

1、Requests模块说明

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

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

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

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

(以上转自Requests官方文档)

2、Requests模块安装

然后执行安装

python setup.py install

个人推荐使用pip安装

pip install requests

也可以使用easy_install安装

easy_install requests

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

3、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)

4、Requests示例

json请求

#!/user/bin/env python
#coding=utf-8
import requests
import json

class url_request():
    def __init__(self):
            """ init """    

if __name__==‘__main__‘:
    headers = {‘Content-Type‘ : ‘application/json‘}
    payload = {‘CountryName‘:‘中国‘,
               ‘ProvinceName‘:‘陕西省‘,
               ‘L1CityName‘:‘汉中‘,
               ‘L2CityName‘:‘城固‘,
               ‘TownName‘:‘‘,
               ‘Longitude‘:‘107.33393‘,
               ‘Latitude‘:‘33.157131‘,
               ‘Language‘:‘CN‘
               }
    r = requests.post("http://www.xxxxxx.com/CityLocation/json/LBSLocateCity",headers=headers,data=payload)
    #r.encoding = ‘utf-8‘
    data=r.json()
    if r.status_code!=200:
        print "LBSLocateCity API Error " + str(r.status_code)
    print data[‘CityEntities‘][0][‘CityID‘] #打印返回json中的某个key的value
    print data[‘ResponseStatus‘][‘Ack‘]
    print json.dumps(data,indent=4,sort_keys=True,ensure_ascii=False) #树形打印json,ensure_ascii必须设为False否则中文会显示为unicode

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

5、参考文档

http://cn.python-requests.org/en/latest/

http://docs.python-requests.org/en/latest/user/quickstart.html

时间: 2024-08-05 19:10:52

Python requests模块学习笔记的相关文章

python requests库学习笔记(上)

尊重博客园原创精神,请勿转载! requests库官方使用手册地址:http://www.python-requests.org/en/master/:中文使用手册地址:http://cn.python-requests.org/zh_CN/latest/: requests库作者Kenneth Reitz个人主页:https://www.kennethreitz.org/: requests库github地址:https://github.com/requests/requests: requ

Python requests模块学习

import requests 下面就可以使用神奇的requests模块了! 1.向网页发送数据 >>> payload = {'key1': 'value1', 'key2': ['value2', 'value3']} >>> r = requests.get('http://httpbin.org/get', params=payload) >>> print(r.url) http://httpbin.org/get?key1=value1&a

python requests库学习笔记(下)

1.请求异常处理 请求异常类型: 请求超时处理(timeout): 实现代码: import requestsfrom requests import exceptions        #引入exceptions A:请求超时 def timeout_request():    try:        response = requests.get(build_uri('user/emails'), timeout=0.1)    except exceptions.Timeout as e:

Python urllib2 模块学习笔记

2015.3.6  urllib2的使用方法大致如下 # 定制Handler处理函数 opener = urllib2.build_opener(ProxyHandler, HTTPHandler) urllib2.install_opener(opener) # 定制URL参数 request = urllib2.Request() request.add_headers(xxx) # 打开URL,返回file-like对象 response = urllib2.urlopen(req) #

【Rollo的Python之路】Python 爬虫系统学习 (二) Requests 模块学习

Requests模块学习: 1.0  Requests 初识 Requests 模块是一个第三方的库,首先我们要安装Requests.用pip安装,先看一下pip是哪个python 的版本. pip --version 然后用pip安装就OK pip install requests 开始要导入 Requests 模块 import requests 然后我们试一下: import requests results = requests.get('https://www.baidu.com')

Edison 蓝牙模块 学习笔记

Edison 蓝牙模块 学习笔记 固定链接:https://www.zybuluo.com/SiberiaBear/note/212527 本笔记基于Intel Edison Bluetooth Guide官方手册完成,如有错误敬请指出. 由于个人能力有限,到最后几节内容一直拖着没有翻译,以后会补上,自己也是边学习边翻译的,还请见谅. Edison 蓝牙模块 学习笔记 基本介绍 Linux集成蓝牙 1 The bluetoothd daemon 2 Configuration 3 Applica

python网络爬虫学习笔记

python网络爬虫学习笔记 By 钟桓 9月 4 2014 更新日期:9月 4 2014 文章目录 1. 介绍: 2. 从简单语句中开始: 3. 传送数据给服务器 4. HTTP头-描述数据的数据 5. 异常 5.0.1. URLError 5.0.2. HTTPError 5.0.3. 处理异常 5.0.4. info和geturl 6. Opener和Handler 7. Basic Authentication 8. 代理 9. Timeout 设置 10. Cookie 11. Deb

Node.js笔记(0003)---Express框架Router模块学习笔记

这段时间一直有在看Express框架的API,最近刚看到Router,以下是我认为需要注意的地方: Router模块中有一个param方法,刚开始看得有点模糊,官网大概是这么描述的: Map logic to route parameters. 大概意思就是路由参数的映射逻辑 这个可能一时半会也不明白其作用,尤其是不知道get和param的执行顺序 再看看源码里面的介绍: Map the given param placeholder `name`(s) to the given callbac

Python subprocess模块学习总结

从Python 2.4开始,Python引入subprocess模块来管理子进程,以取代一些旧模块的方法:如 os.system.os.spawn*.os.popen*.popen2.*.commands.*不但可以调用外部的命令作为子进程,而且可以连接到子进程的input/output/error管道,获取相关的返回信息 一.subprocess以及常用的封装函数 运行python的时候,我们都是在创建并运行一个进程.像Linux进程那样,一个进程可以fork一个子进程,并让这个子进程exec