zoukankan      html  css  js  c++  java
  • Python高手之路【八】python基础之requests模块

    1、Requests模块说明

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

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

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

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

    (以上转自Requests官方文档)

    2、Requests模块安装

    requests模块下载地址:http://docs.python-requests.org/en/latest/user/install/#install

    然后执行安装,解压文件,进入到文件目录,看到setup.py文件,即可!在空白处按住shift键,点右键,选择”在此处打开命令窗口“,然后敲下面的命令

    python setup.py install

    也可以使用pip安装,

    pip install requests

    也可以使用easy_install安装

    easy_install requests

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

    3、Requests模块简单入门

     1 #HTTP请求类型
     2 #get类型
     3 r = requests.get('https://github.com/timeline.json')
     4 #post类型
     5 r = requests.post("http://m.ctrip.com/post")
     6 #put类型
     7 r = requests.put("http://m.ctrip.com/put")
     8 #delete类型
     9 r = requests.delete("http://m.ctrip.com/delete")
    10 #head类型
    11 r = requests.head("http://m.ctrip.com/head")
    12 #options类型
    13 r = requests.options("http://m.ctrip.com/get")
    14 
    15 #获取响应内容
    16 print r.content #以字节的方式去显示,中文显示为字符
    17 print r.text #以文本的方式去显示
    18 
    19 #URL传递参数
    20 payload = {'keyword': '日本', 'salecityid': '2'}
    21 r = requests.get("http://m.ctrip.com/webapp/tourvisa/visa_list", params=payload) 
    22 print r.url #示例为http://m.ctrip.com/webapp/tourvisa/visa_list?salecityid=2&keyword=日本
    23 
    24 #获取/修改网页编码
    25 r = requests.get('https://github.com/timeline.json')
    26 print r.encoding
    27 r.encoding = 'utf-8'
    28 
    29 #json处理
    30 r = requests.get('https://github.com/timeline.json')
    31 print r.json() #需要先import json    
    32 
    33 #定制请求头
    34 url = 'http://m.ctrip.com'
    35 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'}
    36 r = requests.post(url, headers=headers)
    37 print r.request.headers
    38 
    39 #复杂post请求
    40 url = 'http://m.ctrip.com'
    41 payload = {'some': 'data'}
    42 r = requests.post(url, data=json.dumps(payload)) #如果传递的payload是string而不是dict,需要先调用dumps方法格式化一下
    43 
    44 #post多部分编码文件
    45 url = 'http://m.ctrip.com'
    46 files = {'file': open('report.xls', 'rb')}
    47 r = requests.post(url, files=files)
    48 
    49 #响应状态码
    50 r = requests.get('http://m.ctrip.com')
    51 print r.status_code
    52     
    53 #响应头
    54 r = requests.get('http://m.ctrip.com')
    55 print r.headers
    56 print r.headers['Content-Type']
    57 print r.headers.get('content-type') #访问响应头部分内容的两种方式
    58     
    59 #Cookies
    60 url = 'http://example.com/some/cookie/setting/url'
    61 r = requests.get(url)
    62 r.cookies['example_cookie_name']    #读取cookies
    63     
    64 url = 'http://m.ctrip.com/cookies'
    65 cookies = dict(cookies_are='working')
    66 r = requests.get(url, cookies=cookies) #发送cookies
    67 
    68 #设置超时时间
    69 r = requests.get('http://m.ctrip.com', timeout=0.001)
    70 
    71 #设置访问代理
    72 proxies = {
    73            "http": "http://10.10.10.10:8888",
    74            "https": "http://10.10.10.100:4444",
    75           }
    76 r = requests.get('http://m.ctrip.com', proxies=proxies)

    4、Requests示例

    json请求

     1 #!/user/bin/env python
     2 #coding=utf-8
     3 import requests
     4 import json
     5 
     6 class url_request():
     7     def __init__(self):
     8             """ init """    
     9 
    10 if __name__=='__main__':
    11     headers = {'Content-Type' : 'application/json'}
    12     payload = {'CountryName':'中国',
    13                'ProvinceName':'陕西省',
    14                'L1CityName':'汉中',
    15                'L2CityName':'城固',
    16                'TownName':'',
    17                'Longitude':'107.33393',
    18                'Latitude':'33.157131',
    19                'Language':'CN'
    20                }
    21     r = requests.post("http://www.xxxxxx.com/CityLocation/json/LBSLocateCity",headers=headers,data=payload)
    22     #r.encoding = 'utf-8'
    23     data=r.json()
    24     if r.status_code!=200:
    25         print "LBSLocateCity API Error " + str(r.status_code)
    26     print data['CityEntities'][0]['CityID'] #打印返回json中的某个key的value
    27     print data['ResponseStatus']['Ack']
    28     print json.dumps(data,indent=4,sort_keys=True,ensure_ascii=False) #树形打印json,ensure_ascii必须设为False否则中文会显示为unicode

    xml请求

     1 #!/user/bin/env python
     2 #coding=utf-8
     3 import requests
     4 
     5 class url_request():
     6     def __init__(self):
     7             """ init """    
     8 
     9 if __name__=='__main__':
    10     
    11     headers = {'Content-type': 'text/xml'}
    12     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>'
    13     url = 'http://jobws.push.mobile.xxxxxxxx.com/RefreshWeiXInTokenJob/RefreshService.asmx'
    14     r = requests.post(url,headers=headers,data=XML)
    15     #r.encoding = 'utf-8'
    16     data = r.text
    17     print data

     

  • 相关阅读:
    在form里面,放了四个UEditor,怎么在后台分别获取它们值
    在form里面,放了四个UEditor,怎么在后台分别获取它们值
    把二叉树转变为左孩子右兄弟树
    把二叉树转变为左孩子右兄弟树
    把二叉树转变为左孩子右兄弟树
    把二叉树转变为左孩子右兄弟树
    atom安装插件
    atom安装插件
    python request 发送form-data 格式数据
    苏宁易购:前后端分离架构的落地思考
  • 原文地址:https://www.cnblogs.com/ginvip/p/6260476.html
Copyright © 2011-2022 走看看