推荐学习书目
› Learn Python the Hard Way
Python Sites
› PyPI - Python Package Index
› http://diveintopython.org/toc/index.html
› Pocoo
值得关注的项目
› PyPy
› Celery
› Jinja2
› Read the Docs
› gevent
› pyenv
› virtualenv
› Stackless Python
› Beautiful Soup
› 结巴中文分词
› Green Unicorn
› Sentry
› Shovel
› Pyflakes
› pytest
Python 编程
› pep8 Checker
Styles
› PEP 8
› Google Python Style Guide
› Code Style from The Hitchhiker's Guide
bello
V2EX  ›  Python

python requests 模拟登录成功(非 session)后再次请求网站 cookies 被更换,但是用 Session 就可以正常使用,请问下这个过程 Session 做了什么?

  •  
  •   bello · Feb 17, 2016 · 3884 views
    This topic created in 3931 days ago, the information mentioned may be changed or developed.

    在非 Session 的情况下直接用 post 登录网站,能够成功登录并得到 cookies,但是下一次请求时,就发现 cookies 已经被更换了,猜测是第一次登录时得到的 cookie 不正确。
    但是通过 Session 就可以成功登录并继续在登录状态下访问,想请问下这个过程中 Session 做了什么?为什么单独用 cookies 就不能正常。

    bello
    bello
    OP
    Feb 18, 2016
    1
    自己研究了一下,明白了
    原因:
    1. 中间有页面跳转,这些跳转页面的 cookies 没有获得。
    2. response.cookies 每次返回的是该次服务器设置的 cookies,而非累积的(并不像请求中每次请求都将该 domain 下的所有 cookie 都带上),所以必须将每次服务器返回的 cookies 合并,才是该 domain 下的完整 cookies.
    3. 由于之前获得的 cookie 不够完整,服务器检测 cookie 错误,所以重新发新的 cookie ,导致登录状态无法保持。

    所以在这几个环节上, Session 主要完成了:
    #合并新 reponse 的 cookies
    self.cookies.update(new_response.cookies)

    #从 response.history 中获得跳转页面设置的 cookies ,并合并到现有 cookies 中
    if response.history:
    for r in response.history:
    self.cookies.update(r.cookies)

    不知道理解得对不对,但是按照这个思路已经可以在不用 Session 的情况下保持登录状态了。
    虽然还没有人回复,还是谢谢各位。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   927 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 22ms · UTC 22:12 · PVG 06:12 · LAX 14:12 · JFK 17:12
    ♥ Do have faith in what you're doing.