V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
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
ray1888
V2EX  ›  Python

使用 Python 原生库如何复用 cookie

  •  
  •   ray1888 ·
    ray1888 · 2017-08-13 17:16:11 +08:00 · 2123 次点击
    这是一个创建于 2447 天前的主题,其中的信息可能已经有所发展或是发生改变。

    现在在写一个需求类似于爬虫的小脚本,然后那个软件是用 http authentacion 进行认证的 想问问大佬们,我用 cookielib 把 cookie 保存之后,如何再去使用他来登陆网站应用? 现在的问题是不能复用 cookie 的我,我直接访问,会出现 401 认证错误。所以如何解决这个问题呢?

    10 条回复    2017-08-14 13:35:51 +08:00
    ray1888
        1
    ray1888  
    OP
       2017-08-13 17:19:50 +08:00
    登陆的部分函数是这样的:
    base64string = base64.encodestring(
    "%s:%s" % (username, password))[:-1] # 注意哦,这里最后会自动添加一个\n
    authheader = "Basic %s" % base64string
    cookie = cookielib.CookieJar()
    handler = urllib2.HTTPCookieProcessor(cookie)
    opener = urllib2.build_opener(handler)
    req = urllib2.Request(url=url)
    req.add_header("Authorization", authheader)
    response = opener.open(req)
    ihciah
        2
    ihciah  
       2017-08-13 18:33:38 +08:00 via iPad
    无脑 pickle 吧
    golmic
        3
    golmic  
       2017-08-13 18:42:58 +08:00
    为什么一定要用原声库呢? requests 不好么?
    wolong
        4
    wolong  
       2017-08-13 18:53:52 +08:00
    用 requests 很方便啊。
    ray1888
        5
    ray1888  
    OP
       2017-08-13 19:58:25 +08:00
    @golmic 环境依赖问题,要求不能用第三方的库
    linhua
        6
    linhua  
       2017-08-13 20:07:54 +08:00
    pickle 序列化、反序列化
    tempdban
        7
    tempdban  
       2017-08-14 01:17:36 +08:00 via Android
    不说别的 你知道为啥会加\n 么 你用错了
    lieh222
        8
    lieh222  
       2017-08-14 09:11:56 +08:00
    http authentacion 认证的一般不用管 cookie 了,所有请求头部都带上认证信息就行了
    Luckyray
        9
    Luckyray  
       2017-08-14 10:41:02 +08:00
    不能用第三方库?难道用的 ios 上的 Pythonista ?
    fisher335
        10
    fisher335  
       2017-08-14 13:35:51 +08:00
    python 牛 B 的地方就在第三方库~ 不让用的话的确是扬短避长啊~
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5370 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 07:23 · PVG 15:23 · LAX 00:23 · JFK 03:23
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.