zoukankan      html  css  js  c++  java
  • python requests模块

    安装 Requests

    在你已经安装好python的前提下:

    pip install requests

    如果你没有安装 pip (啧啧),这个 Python installation guide 可以带你完成这一流程。

    获得源码

    Requests 一直在 Github 上积极地开发,你可以一直从这里获取到代码。

    你可以克隆公共版本库:

    git clone git://github.com/kennethreitz/requests.git

    发送请求

    requests模块用于是发送网络请求

    导入模块

    import requests

    尝试获取某个网页,支持HTTP的多种请求类型(GET,PUT,DELETE,HEAD ,OPTIONS )

    >>> r = requests.get('https://github.com/timeline.json')
    >>> r = requests.post("http://httpbin.org/post")
    >>> r = requests.put("http://httpbin.org/put")
    >>> r = requests.delete("http://httpbin.org/delete")
    >>> r = requests.head("http://httpbin.org/get")
    >>> r = requests.options("http://httpbin.org/get")

    传递 URL 参数

    如果你是手工构建 URL,那么数据会以键/值对的形式置于 URL 中,跟在一个问号的后面。

    Requests 允许你使用 params 关键字参数,以一个字符串字典来提供这些参数。

    import requests
    
    args = {'arg1': 'value1', 'arg2': 'value2'}
    response = requests.get('http://www.9158.com', params=args)
    print(response.url)
    http://www.9158.com/?arg1=value1&arg2=value2

    响应内容

    返回结果response是一个request response类型

    import requests
    
    response = requests.get('http://www.9158.com')
    print(response.text)
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional/............

     Requests 会自动解码来自服务器的内容。大多数 unicode 字符集都能被无缝地解码。

    请求发出后,Requests 会基于 HTTP 头部对响应的编码作出有根据的推测。当你访问 r.text 之时,Requests 会使用其推测的文本编码。你可以找出 Requests 使用了什么编码,并且能够使用r.encoding 属性来改变它:

    import requests
    
    response = requests.get('http://www.9158.com')
    print(response.encoding)
    response.encoding = 'utf-8'
    print(response.encoding)
    gb2312
    utf-8

    二进制响应内容

    你也能以字节的方式访问请求响应体,对于非文本请求:

    >>>response = requests.get('http://image1.miaobolive.com/avator/2018-01/15/17/20180115172402_43697510_640.png')
    b'xffxd8xffxe0x00x10JFIFx00x01x01x01....

    Requests 会自动为你解码 gzip 和 deflate 传输编码的响应数据。

    JSON 响应内容

    Requests 中也有一个内置的 JSON 解码器,助你处理 JSON 数据:

    response = requests.get('https://room.9158.com/live/getanchoronlinetime.aspx?starttime=201803051100&endtime=201803051200')
    print(response.json())
    {'code': 'A00006', 'msg': '成功', 'data': [{'idx':...............

    定制请求头

    更加复杂的 POST 请求

    响应状态码

    响应头

    Cookie

    重定向与请求历史

    超时

    request 基本用法

    http://docs.python-requests.org/zh_CN/latest/user/quickstart.html#id3

    高级用法

    会话对象

    请求与响应对象

    代理

    http://docs.python-requests.org/zh_CN/latest/user/advanced.html#advanced

  • 相关阅读:
    SSLZYC 洛谷P2055 假期的宿舍
    SSLZYC 2601 (洛谷P1756)【24题】飞行员配对方案问题
    SSLZYC POJ 3264 平衡的阵容
    SSLZYC 2432 面积最大
    SSLZYC 2433 文件名排序
    Structure of a C program: Preprocessor directives (#include <stdlib.h>, #define)
    Basic vim Commands
    UNIX Copying Files Remotely Examples(scp/pscp)
    ssh command in Linux with Example
    UNIX Copying a File
  • 原文地址:https://www.cnblogs.com/LouisZJ/p/8631176.html
Copyright © 2011-2022 走看看