代码之家  ›  专栏  ›  技术社区  ›  Siddharth Chabra

Pythons请求。会话cookie检索问题

  •  0
  • Siddharth Chabra  · 技术社区  · 7 年前

    我试图从网站上收集数据,当我使用requests.session时,从网站获取cookies似乎有问题。下面的代码可以更好地解释

    import requests
    headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.84 Safari/537.36'}
    url = "https://www.nseindia.com"
    r_without_headers = requests.get(url)
    print("response code",r_without_headers.status_code)
    print("Resp no header cookies ",r_without_headers.cookies.get_dict())
    r_with_headers = requests.get(url,headers = headers)
    print("response code",r_with_headers.status_code)
    print("Resp with header cookies ",r_with_headers.cookies.get_dict())
    
    s1 = requests.session()
    s1_req = s1.get(url)
    print("response code",s1_req.status_code)
    print("Session no header Cookies ", s1.cookies.get_dict())
    print("Session no header Response Cookies", s1_req.cookies.get_dict())
    
    s2 = requests.session()
    s2.headers = headers
    s2_req = s2.get(url)
    print("response code",s2_req.status_code)
    print("Session with header Cookies ", s2.cookies.get_dict())
    print("Session with header Response Cookies", s2_req.cookies.get_dict())
    

    输出

    response code 200
    Req no header cookies  {}
    response code 200
    Req with header cookies  {'ak_bmsc': 'F4040D045001A7CD57BBC58C09C9117F174C9D8E21750000240B665BDDE23467~plhUo272BWU9CTPiQAEJgiZ07qX/BOE0n6iOU8y9pewbmXipo8de1YROpMw6AEtjQDgdt3x+M/2QDATjSAtaRiDVlsDGZfohfsymElg0Xpq0Uta3OYSOSe2B48eg2lJD0CMios+0eqatEro6XvEkYAy+4D14EUHAE/eRp5oVUOpVL6JR8WMNNFoE6Xo7xYQtfLFu8hS1sUNABrYkr6XNFGY3YnkZmawa7imZswMI4tICc='}
    response code 200
    Session no header Cookies  {}
    Session no header Request Cookies {}
    response code 200
    Session with header Cookies  {}
    Session with header Request Cookies {}
    

    这个 发行

    网站显然需要用户代理集来提供cookie,所以当我使用用户代理集发出get请求时,我会得到预期的cookie,而没有用户代理集,我就不会。

    当我对requests.session进行相同的尝试时,我没有同时获得带有和不带头的响应cookie?

    这个 问题

    为什么会这样?我使用的会话是否不正确或网站是否已损坏?(如果是这样的话,我不会感到惊讶)

    如何使用会话获取cookies?

    我目前的想法是发送一个简单的get请求,检索cookies并在会话中手动设置cookies。但这似乎不正确,如果在后续请求中修改了cookie,则无法保证会话将更新cookie,因为原始会话首先无法检索cookie。我不想让写我的整个代码使用裸请求和手动传输cookie到后续的请求。

    1 回复  |  直到 7 年前
        1
  •  1
  •   AKX Bryan Oakley    7 年前

    问题是您正在覆盖会话的 headers 对象(在引擎盖下不是实际的dict)和自己的dict。

    只需更新它:

    s2.headers.update(headers)
    

    例如。

    import requests
    url = "https://www.nseindia.com"
    s2 = requests.session()
    s2.headers.update({'User-Agent': 'Mozilla/5.0'})
    s2_req = s2.get(url)
    print("Session with header Cookies ", s2.cookies.keys())
    

    愉快地输出

    Session with header Cookies  ['ak_bmsc']