fangwenxue
V2EX  ›  问与答

requests header cookie

  •  
  •   fangwenxue · Apr 23, 2020 · 1244 views
    This topic created in 2235 days ago, the information mentioned may be changed or developed.
    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 replies    2020-04-23 21:26:28 +08:00
    ClericPy
        1
    ClericPy  
       Apr 23, 2020
    代码这是删了很多关键东西啊...

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

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

    毕竟我也不知道你的 kwargs 是哪儿创建的
    fangwenxue
        2
    fangwenxue  
    OP
       Apr 23, 2020
    @ClericPy 可以确定 kwargs 里面的 headers 是有 cookie 的
    fangwenxue
        3
    fangwenxue  
    OP
       Apr 23, 2020
    ```
    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  
       Apr 23, 2020
    @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'}
    ```
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1111 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 35ms · UTC 23:45 · PVG 07:45 · LAX 16:45 · JFK 19:45
    ♥ Do have faith in what you're doing.