zoukankan      html  css  js  c++  java
  • requests--重定向,序列化

    重定向

    默认情况下,除了 HEAD, Requests 会自动处理所有重定向。可以使用响应对象的 history 方法来追踪重定向。

    Response.history 是一个 Response 对象的列表,为了完成请求而创建了这些对象。这个对象列表按照从最老到最近的请求进行排序。例如,12306 将所有的 HTTP 请求重定向到 HTTPS

    import requests
    requests.packages.urllib3.disable_warnings()
    
    r = requests.get('http://www.12306.cn/',verify=False)
    print(r.url)
    print(r.status_code)
    print(r.history)

    结果:

    https://www.12306.cn/index/
    200
    [<Response [302]>, <Response [302]>]

    如果你使用的是GET、OPTIONS、POST、PUT、PATCH 或者 DELETE,那么你可以通过 allow_redirects 参数禁用重定向处理:

    import requests
    requests.packages.urllib3.disable_warnings()
    
    r = requests.get('http://www.12306.cn/',verify=False, allow_redirects=False)
    print(r.url)
    print(r.status_code)
    print(r.history)

    结果:

    http://www.12306.cn/
    302
    []

    如果你使用了 HEAD,你也可以启用重定向:

    >>> r = requests.head('http://github.com', allow_redirects=True)
    >>> r.url
    'https://github.com/'

    >>> r.history [<Response [301]>]

    序列化

    json.dumps()

     json.dumps()用于将dict类型的数据转成str,因为如果直接将dict类型的数据写入json文件中会发生报错,因此在将数据写入时需要用到该函数。

    import json
    
    name_emb = {'a': '1111', 'b': '2222', 'c': '3333', 'd': '4444'}
    
    jsObj = json.dumps(name_emb)
    
    print(name_emb)
    print(jsObj)
    
    print(type(name_emb))

    结果:

    {'a': '1111', 'b': '2222', 'c': '3333', 'd': '4444'}
    {"a": "1111", "b": "2222", "c": "3333", "d": "4444"}
    <class 'dict'>
    json.loads()

     json.loads()用于将str类型的数据转成dict。

    import json
    
    name_emb = {'a': '1111', 'b': '2222', 'c': '3333', 'd': '4444'}
    
    jsDumps = json.dumps(name_emb)
    
    jsLoads = json.loads(jsDumps)
    
    print(name_emb)
    print(jsDumps)
    print(jsLoads)
    
    print(type(name_emb))
    print(type(jsDumps))
    print(type(jsLoads))

    结果:

    {'a': '1111', 'b': '2222', 'c': '3333', 'd': '4444'}
    {"a": "1111", "b": "2222", "c": "3333", "d": "4444"}
    {'a': '1111', 'b': '2222', 'c': '3333', 'd': '4444'}
    <class 'dict'>
    <class 'str'>
    <class 'dict'>
  • 相关阅读:
    VIJOS-P1340 拯救ice-cream(广搜+优先级队列)
    uva 11754 Code Feat
    uva11426 GCD Extreme(II)
    uvalive 4119 Always an Interger
    POJ 1442 Black Box 优先队列
    2014上海网络赛 HDU 5053 the Sum of Cube
    uvalive 4795 Paperweight
    uvalive 4589 Asteroids
    uvalive 4973 Ardenia
    DP——数字游戏
  • 原文地址:https://www.cnblogs.com/zouzou-busy/p/11407772.html
Copyright © 2011-2022 走看看