Python 自动登录网站(处理Cookie)

def login():
    cj = cookielib.CookieJar()
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
    login_url = r'http://zhixing.bjtu.edu.cn/member.php?mod=logging&action=login&loginsubmit=yes&infloat=yes&lssubmit=yes&inajax=1'
    login_data = urllib.urlencode({'cookietime': '2592000', 'handlekey': 'ls', 'password': 'xxx',
            'quickforward': 'yes', 'username': 'digiter'})
    opener.open(login_url, login_data)
    return opener

返回以后只需要设置url和data就可以Post了。

注意不要在request里设置header,这是因为cookie也是header,如果设置header会导致没有cookie,也就没有登录

request = urllib2.Request(
        url=r'http://zhixing.bjtu.edu.cn/forum.php?mod=post&action=newthread&fid=601&extra=&topicsubmit=yes',
        data=param
    )
    print opener.open(request).read()

轻松搞定设置DiscuzX主题分类的功能(cookie要模拟浏览器,这里是模仿firefox)

# -*- coding: utf-8 -*-
'''
Created on Dec 24, 2011

@author: rush
'''
import urllib, urllib2, cookielib
import os, time

headers = []

def login():
    cj = cookielib.CookieJar()
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
    login_url = r'http://zhixing.bjtu.edu.cn/member.php?mod=logging&action=login&loginsubmit=yes&infloat=yes&lssubmit=yes&inajax=1'
    login_data = urllib.urlencode({'cookietime': '2592000', 'handlekey': 'ls', 'password': 'xxx',
            'quickforward': 'yes', 'username': 'GuoYuan'})
    opener.addheaders = [('Host', 'zhixing.bjtu.edu.cn'),
                       ('User-Agent', 'Mozilla/5.0 (Ubuntu; X11; Linux i686; rv:8.0) Gecko/20100101 Firefox/8.0'),
                       ('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'),
                       ('Accept-Language', 'en-us,en;q=0.5'),
                       ('Accept-Encoding', 'gzip, deflate'),
                       ('Accept-Charset', 'ISO-8859-1,utf-8;q=0.7,*;q=0.7'),
                       ('Connection', 'keep-alive'),
                       ('Referer', 'http://zhixing.bjtu.edu.cn/forum.php'),]
    opener.open(login_url, login_data)
    return opener

if __name__ == '__main__':
    opener = login()

    url = r'http://zhixing.bjtu.edu.cn/forum.php?mod=topicadmin&action=moderate&optgroup=2&modsubmit=yes&infloat=yes&inajax=1'    
    data = {'fid': '601', 'formhash': '0cdd1596', 'frommodcp': '', 'handlekey': 'mods',
             'listextra': 'page%3D62', 'moderate[]': '496146', 'operations[]': 'type', 'reason': '...',
             'redirect': r'http://zhixing.bjtu.edu.cn/thread-496146-1-1.html', 'typeid': '779'}
    data2 = [(k, v) for k,v in data.iteritems()]
    
    cnt = 0
    for tid in range(493022, 496146 + 1):
        cnt += 1
        if cnt % 20 == 0: print
        print tid,
        
        data2.append(('moderate[]', str(tid)))
        if cnt % 40 == 0 or cnt == 496146:
            request = urllib2.Request(url=url, data=urllib.urlencode(data2))
            print opener.open(request).read()
            data2 = [(k, v) for k,v in data.iteritems()]

相关推荐