V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
fangwenxue
V2EX  ›  问与答

requests header cookie

  •  
  •   fangwenxue · 2020-04-23 20:34:32 +08:00 · 802 次点击
    这是一个创建于 1475 天前的主题,其中的信息可能已经有所发展或是发生改变。
    self.request = requests.session()
    self.headers = {
    	'User-Agent': FakerUa.get_ua(),
    }
    

    方式一

    • cookie 没带过去
    self.headers['Cookie'] = 'adc=1'
    kwargs.setdefault('headers', self.headers)
    kwargs.setdefault('timeout', 20)
    response = self.request.get(url, **kwargs)
    

    方式二

    • cookie 带过去了
    cookies = dict(adc='1')
    response = self.request.get(url, cookies=cookies, **kwargs)
    

    方式一为什么带不过去

    4 条回复    2020-04-23 21:26:28 +08:00
    ClericPy
        1
    ClericPy  
       2020-04-23 20:53:50 +08:00
    代码这是删了很多关键东西啊...

    把最小测试代码发上来不好么, 反正有 httpbin

    就目前所看到的来说, 我正常使用不会用 setdefault, 而是直接 kwargs['headers'] = self.headers

    毕竟我也不知道你的 kwargs 是哪儿创建的
    fangwenxue
        2
    fangwenxue  
    OP
       2020-04-23 21:03:06 +08:00
    @ClericPy 可以确定 kwargs 里面的 headers 是有 cookie 的
    fangwenxue
        3
    fangwenxue  
    OP
       2020-04-23 21:06:43 +08:00
    ```
    print(kwargs)
    {'headers': {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.999.85 Safari/537.36', 'Cookie': 'adc=1'}, 'timeout': 20, 'proxies': {'http': 'socks5://127.0.0.1:1080', 'https': 'socks5://127.0.0.1:1080'}}


    print(response.request.headers)
    {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.999.85 Safari/537.36', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive'}

    ```
    ClericPy
        4
    ClericPy  
       2020-04-23 21:26:28 +08:00
    @fangwenxue #3 怀疑是服务端不认啊...

    用 httpbin 写的最小测试代码

    ```python
    # -*- coding: utf-8 -*-

    import requests

    r = requests.get('http://httpbin.org/get', cookies={'abc': '1'})
    print(r.json())
    # {'args': {}, 'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Cookie': 'abc=1', 'Host': 'httpbin.org', 'User-Agent': 'python-requests/2.23.0', 'X-Amzn-Trace-Id': 'Root=1-5ea196fd-2ad50b072b6c252274cf4b3c'}, 'origin': '119.181.173.152', 'url': 'http://httpbin.org/get'}
    r = requests.get('http://httpbin.org/get', headers={'Cookie': 'abc=1'})
    print(r.json())
    # {'args': {}, 'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Cookie': 'abc=1', 'Host': 'httpbin.org', 'User-Agent': 'python-requests/2.23.0', 'X-Amzn-Trace-Id': 'Root=1-5ea19718-fd0b6b6acd989d0e3af1604a'}, 'origin': '119.181.173.152', 'url': 'http://httpbin.org/get'}
    ```
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1585 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 17:11 · PVG 01:11 · LAX 10:11 · JFK 13:11
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.