V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐学习书目
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 · Aug 4, 2013 · 3752 views
    This topic created in 4662 days ago, the information mentioned may be changed or developed.
    # -*- 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 replies    1970-01-01 08:00:00 +08:00
    timonwong
        1
    timonwong  
       Aug 4, 2013   ❤️ 1
    没有Cookie
    你可以试试用cookielib.CookieJar保存相关Cookie:
    cookie = cookielib.CookieJar()
    # With Cookie
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie))

    然后用这个opener操作
    clino
        2
    clino  
       Aug 4, 2013   ❤️ 1
    没用过urllib2,我基本上用的是requests
    不过目测是不是应该给 urlopen 加上 data 参数?
    urllib2.urlopen(url[, data][, timeout])
    而这个data参数要给登陆以后返回的session cookie内容
    alexrezit
        3
    alexrezit  
       Aug 4, 2013 via iPhone   ❤️ 1
    @timonwong
    正解.
    tedd
        4
    tedd  
    OP
       Aug 4, 2013
    @timonwong 原来如此,opener操作是关键,感谢tim
    wzzyj8
        5
    wzzyj8  
       Aug 4, 2013   ❤️ 1
    可以试试看这个:http://jeanphix.me/Ghost.py/
    如果你需要模拟一些浏览器操作,ghost.py还是挺好用的
    ushuz
        6
    ushuz  
       Aug 4, 2013
    requests, for human.
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3106 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 37ms · UTC 03:35 · PVG 11:35 · LAX 20:35 · JFK 23:35
    ♥ Do have faith in what you're doing.