使用python登录cookie

时间:2013-12-04 17:09:05

标签: python cookies mechanize

我被建议使用Mechanize Module通过python脚本登录网站,虽然我原本想使用urllib / urllib2。现在,我已经阅读了Mechanize的文档,它只是不起作用。我已经在我的脚本中添加了cookie支持,而且似乎Mechanize不会完成这项工作。有人可以看看我的代码,并告诉我,如果我错过了什么?我的脚本创建的OUTPUT(MechanizeDat.html)应该在我登录后显示页面,其中应该包括我的用户名和帐户等,...虽然它目前只是重新显示登录屏幕。出于显而易见的原因,我从脚本中发出了我的密码/用户名,但你会得到这个想法(你应该得到'错误的用户名/密码组合',但你会看到你只是登录屏幕):

{
    import mechanize
    import cookielib
    import urllib
    import logging
    import sys

def main():

    br = mechanize.Browser()
    cj = cookielib.LWPCookieJar()
    br.set_cookiejar(cj)

    br.set_handle_equiv(True)
    br.set_handle_gzip(True)
    br.set_handle_redirect(True)
    br.set_handle_referer(True)
    br.set_handle_robots(False)

    br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)

    r= br.open('http://www.zulutrade.com/login')

    # Select the second (index one) form
    br.select_form(nr=0)

    #for control in br.form.controls:
    #  print control

    # User credentials
    br.form['ctl00$main$tbUsername'] = 'MYUSERNAME'
    br.form['ctl00$main$tbPassword'] = 'MYPASSWORD'

    #br.form['3'] = 'Sign In'

    # Login
    br.submit()

    # Open up comment page
    posting = 'https://www.zulutrade.com/user#dashboard'
    #rval = 'PoopSandwiches'
    # you can get the rval in other ways, but this will work for testing

    r = br.open(posting)

    # You need the 'uh' value from the first form
    #br.select_form(nr=0)
    #uh = br.form['uh']

    #br.select_form(nr=7)
    #thing_id = br.form['thing_id']
    #id = '#' + br.form.attrs['id']
    # The id that gets posted is the form id with a '#' prepended.

    #data = {'uh':uh, 'thing_id':thing_id, 'id':id, 'renderstyle':'html', 'r':rval, 'text':"Your text here!"}
    #new_data_dict = dict((k, urllib.quote(v).replace('%20', '+')) for k, v in data.iteritems())

    # not sure if the replace needs to happen, I did it anyway
    #new_data = 'thing_id=%(thing_id)s&text=%(text)s&id=%(id)s&r=%(r)s&uh=%(uh)s&renderstyle=%(renderstyle)s' %(new_data_dict)

    # not sure which of these headers are really needed, but it works with all
    # of them, so why not just include them.
    req = mechanize.Request('https://www.zulutrade.com/user#dashboard', None) #None was new_data
    req.add_header('Referer', posting)
    req.add_header('Accept', ' application/json, text/javascript, */*')
    req.add_header('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8')
    req.add_header('X-Requested-With', 'XMLHttpRequest')
    cj.add_cookie_header(req)
    res = mechanize.urlopen(req)
    html=res.read()
    file=open('MechanizeDat.html','wb')
    file.write(html)
    file.close()

main()

}

0 个答案:

没有答案
相关问题