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
tedd
V2EX  ›  Python

小白用urllib写了个自动登陆的脚本,登陆页面成功但而后访问其他页面依旧返回未登陆

  •  
  •   tedd · 2013-08-04 09:13:05 +08:00 · 3158 次点击
    这是一个创建于 3912 天前的主题,其中的信息可能已经有所发展或是发生改变。
    # -*- coding: utf-8 -*-
    import urllib, urllib2

    loginUrl = #登陆页面地址
    tUrl = #私密页面地址

    postdata = urllib.urlencode({
    'username':'username',
    'password':'password',
    'loginsubmit':'登陆',
    })

    req = urllib2.Request(loginUrl, data=postdata)
    content = urllib2.urlopen(req).read()
    print content #成功登陆
    content2 = urllib2.urlopen(tUrl).read()
    print content2 #提示未登陆
    6 条回复    1970-01-01 08:00:00 +08:00
    timonwong
        1
    timonwong  
       2013-08-04 09:17:14 +08:00   ❤️ 1
    没有Cookie
    你可以试试用cookielib.CookieJar保存相关Cookie:
    cookie = cookielib.CookieJar()
    # With Cookie
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie))

    然后用这个opener操作
    clino
        2
    clino  
       2013-08-04 09:19:56 +08:00   ❤️ 1
    没用过urllib2,我基本上用的是requests
    不过目测是不是应该给 urlopen 加上 data 参数?
    urllib2.urlopen(url[, data][, timeout])
    而这个data参数要给登陆以后返回的session cookie内容
    alexrezit
        3
    alexrezit  
       2013-08-04 09:26:44 +08:00 via iPhone   ❤️ 1
    @timonwong
    正解.
    tedd
        4
    tedd  
    OP
       2013-08-04 09:32:20 +08:00
    @timonwong 原来如此,opener操作是关键,感谢tim
    wzzyj8
        5
    wzzyj8  
       2013-08-04 09:38:02 +08:00   ❤️ 1
    可以试试看这个:http://jeanphix.me/Ghost.py/
    如果你需要模拟一些浏览器操作,ghost.py还是挺好用的
    ushuz
        6
    ushuz  
       2013-08-04 11:52:14 +08:00
    requests, for human.
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2608 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 10:48 · PVG 18:48 · LAX 03:48 · JFK 06:48
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.