推荐学习书目
› 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 · 4170 views
    This topic created in 4841 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
    timonwong
    Aug 4, 2013❤️1
    1
    没有Cookie
    你可以试试用cookielib.CookieJar保存相关Cookie:
    cookie = cookielib.CookieJar()
    # With Cookie
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie))

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