zoukankan      html  css  js  c++  java
  • python之requests库使用问题汇总

    一、请求参数类型

    1.get

    requests.get(url, params, cookies=cookies)

    url:字符串;

    params:字典类型,可以为空;

    cookies:字典类型,可以为空;

    无headers参数;

    2.post

    requests.post(url, data, headers=headers, cookies=cookies)   

    post请求根据编码方式有可分为:application/x-www-form-urlencoded、multipart/form-data、application/json、text/xml。

    application/x-www-form-urlencoded 

    浏览器的原生 form 表单,如果不设置 enctype 属性,那么最终就会以 application/x-www-form-urlencoded 方式提交数据。

    data:字典类型;

    headers:字典类型,可以为空;

    cookies:字典类型,可以为空;

    url = 'http://httpbin.org/post'
    d = {'key1': 'value1', 'key2': 'value2'}
    r = requests.post(url, data=d)
    print r.text

    application/json

    data:json类型;

    headers:字典类型,可以为空;

    cookies:字典类型,可以为空;

    url = 'http://httpbin.org/post'
    s = json.dumps({'key1': 'value1', 'key2': 'value2'})
    r = requests.post(url, data=s)
    print r.text

    其他参考https://www.cnblogs.com/insane-Mr-Li/p/9145152.html

    3.put

    requests.put(url, data, headers=headers, cookies=cookies)  

    与post基本一致

    4.delete

    requests.delete(url, headers=headers, cookies=cookies)  

    headers:字典类型,可以为空;

    cookies:字典类型,可以为空;

    无data参数;

    二、数据类型转换

    a='{"errno":0,"errmsg":"这是一个实例","unassigned":0,"total":0,"list":null}'

    字符串转换成字典

    字符串中无值为null时,可以使用eval();

    字符串中是单引号时,可以使用eval();

    字符串中有值为null时,可以使用json.loads();

    字符串中是双引号时,可以使用json.loads();

    参考https://www.cnblogs.com/lansan0701/p/9917094.html

    字典转化成字符串

    json.dumps();

    字典中有中文时,需加 ensure_ascii=False 参数;

    >>> a='{"errno":0,"errmsg":"这是一个实例","unassigned":0,"total":0,"list":null}'
    >>> eval(a)
    NameError: name 'null' is not defined
    >>> import json
    >>> json.loads(a)
    {'total': 0, 'errno': 0, 'errmsg': '这是一个实例', 'unassigned': 0, 'list': None}
    >>> json.dumps(a)
    '"{\"errno\":0,\"errmsg\":\"\u8fd9\u662f\u4e00\u4e2a\u5b9e\u4f8b\",\"unassigned\":0,\"total\":0,\"list\":null}"'
    >>> json.dumps(a, ensure_ascii=False)
    '"{\"errno\":0,\"errmsg\":\"这是一个实例\",\"unassigned\":0,\"total\":0,\"list\":null}"'

    三、获取cookies

    res = requests.post('http://www.xxx.com', {'username':'lilei', 'password':'123456'})   

    cookies = res.cookies #此处类型为<class 'requests.cookies.RequestsCookieJar'>

    cookies = requests.utils.dict_from_cookiejar(cookies) #将CookieJar转为字典

  • 相关阅读:
    Delphi 2010下安装IOComp
    为自定义控件的某个属性添加像Winform控件中属性的注释
    C#WinForm仿qq窗体拖到windows窗体边上时,自动隐藏C#WinForm
    给图片添加水印,解决GIF添加水印的问题(无法从带有索引像素格式的图像创建 Graphics 对象)
    怎样把Image数据放入数据库
    取消IE“已限制此网页运行可以访问计算机的脚本
    sql 二进制文件的导入导出
    [转载]数据结构笔试题基础
    [转载]搜索算法(含基本搜索算法与深度搜索与广度搜索算法等思想)
    [转载]面试笔试总结
  • 原文地址:https://www.cnblogs.com/lansan0701/p/9984316.html
Copyright © 2011-2022 走看看