zoukankan      html  css  js  c++  java
  • requests库的学习——跟随官方文档

    发送GET请求:

    import requests
    r=requests.get("http://www.kekenet.com/")

    如果需要传递参数可以有以下几种方法:

    import requests
    r=requests.get("http://httpbin.org/get?key1=value1&key2=value2")

    或者

    payload = {'key1': 'value1', 'key2': 'value2'}
    r=requests.get("https://httpbin.org/get",params=payload)

    其中payload里面的值也可以是列表类型的,如

    payload = {'key1': 'value1', 'key2': ['value2', 'value3']}

    相当于访问url:https://httpbin.org/get?key1=value1&key2=value2&key2=value3

    定制请求头:

    headers={'user-agent': 'my-app/0.0.1'}
    r=requests.get("https://api.github.com/some/endpoint",headers=headers)

    读取内容:

    如果是读取非文本数据,可以使用r.content来读取二进制数据

    如果需要读取网页内容,可以使用r.text,Requests会基于Http头部进行对编码推测,并选择合适的解码方式。你可以使用r.encoding来查看编码方式,如果返回的网页内容出现了乱码,可以通过查看r.content的头部编码来修改r.encoding的值重新进行r.text的提取,这样就会得到正确的内容了。

    r=requests.get("http://www.kekenet.com/")
    print(r.text)#这里是乱码,
    print(r.encoding)#可以查看出Requests推测的内容编码方式
    r.encoding="UTF-8" #通过查看网页的编码方式来修改r.encoding
    print(r.text)

    处理json数据:

    Requests内部有一个json解码器,能够帮你处理json数据

    r=requests.get("https://api.github.com/events")
    t=r.json()

    发送POST请求:

    发送post请求需要添加data,

    data可以是dict类型,也可以是str类型,也可以是元祖类型

    payload = (('key1', 'value1'), ('key1', 'value2'))
    r = requests.post('https://httpbin.org/post', data=payload)
    print(r.text)

    响应状态码:

    可以通过

    r.status_code

    来查看响应状态码;响应状态码是表示是否成功访问。一般正常是200

    响应头:

    可以通过

    r.headers

    来查看响应头

  • 相关阅读:
    POJ1061:青蛙的约会+POJ2115C Looooops+UVA10673Play with Floor and Ceil(扩展欧几里得)
    扩展欧几里得算法
    常用数学公式
    实训作业
    sdut 迷之容器(线段树+离散化)
    HDU1556:Color the ball(简单的线段树区域更新)
    HDU1698:Just a Hook(线段树区域更新模板题)
    32位的二进制数
    HDU5139:Formula(找规律+离线处理)
    HDU5023:A Corrupt Mayor's Performance Art(线段树区域更新+二进制)
  • 原文地址:https://www.cnblogs.com/goforwards/p/8969972.html
Copyright © 2011-2022 走看看