Python 自動登入網站(處理Cookie)
Python代碼
- 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,也就沒有登入
Python代碼
- 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()
輕鬆搞定設定Discuz X主題分類的功能(cookie要類比瀏覽器,這裡是模仿firefox)Python代碼
- # -*- 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()]