#! /usr/bin/env python # -*- coding: utf-8 -*- import urllib2, urllib, cookielib, re, time class Robot(object): def __init__(self, forumUrl, userName, password, proxy = None): ''' 初始化论坛url、用户名、密码和代理服务器 ''' self.forumUrl = forumUrl self.userName = userName self.password = password self.formhash = '' self.isLogon = False self.isSign = False self.xq = '' self.jar = cookielib.CookieJar() if not proxy: self.openner = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.jar)) #设置cookie变量 else: self.openner = urllib2.build_opener( urllib2.HTTPCookieProcessor(self.jar), urllib2.ProxyHandler({'http' : proxy})) urllib2.install_opener(openner)
def login(self): ''' 登录论坛 ''' url = self.forumUrl + "/bbs/member.php?mod=logging&action=login&loginsubmit=yes&infloat=yes&lssubmit=yes&inajax=1"; #登陆地址与下面的回帖地址至关重要,我这里用个的fiddler工具抓包获取的webforms的数据
postData = urllib.urlencode({ 'username': self.userName, 'password': self.password, 'answer': '', 'cookietime': '2592000', 'handlekey': 'ls', 'quickforward': 'yes', 'fastloginfield': 'username' }) user_agent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) Chrome/49.0.2623.112' headers = { 'User-Agent' : user_agent } req = urllib2.Request(url,data=postData,headers=headers) content = self.openner.open(req).read() #使用cookie去访问页面,并保存cookie到变量,后面访问其他页面会使用 #print content if str(11040) in content: self.isLogon = True print 'logon success!' self.initFormhashXq() else: print 'logon faild!'
def initFormhashXq(self): ''' 获取formhash''' content = self.openner.open(self.forumUrl + '/bbs/forum.php?mod=viewthread&tid=39765&extra=page%3D1').read().decode('utf-8') #self.openner为上面保存到的cookie变量值,通过它可以去访问其它页面。这里的页面是一个帖子的地址。随意找的一个 为了获取formhash值
#print content rows = re.findall(r'<input type=\"hidden\" name=\"formhash\" value=\"(.*?)\" />', content) #正则匹配找到formhash值 if len(rows)!=0: self.formhash = rows[0] print 'formhash is: ' + self.formhash else: print 'none formhash!'
def reply(self, tid, subject = u'',msg = u'支持玉树临风,人见人爱的高先生~~嘻嘻'): ''' 回帖 ''' url = self.forumUrl + '/bbs/forum.php?mod=post&action=reply&fid=822&tid={}&extra=page%3D1&replysubmit=yes&infloat=yes&handlekey=fastpost&inajax=1'.format(tid) #url为要回帖的地址
postData = urllib.urlencode({'formhash': self.formhash, 'message': msg.encode('utf-8'), 'subject': subject.encode('utf-8'), 'posttime':int(time.time()) })
#定义一个postdata数据 req = urllib2.Request(url,postData) content = self.openner.open(req).read().decode('utf-8') #print content if u'发布成功' in content: print 'reply success!' else: print 'reply faild!'
if __name__ == '__main__': robot = Robot('http://192.168.150.1', 'admin', 'admin') robot.login() robot.reply(39765)
说明:到此已实现论坛的自动登录回帖功能,由于图片上传不了很多细节没描述清楚,有问题可以加群244844732(群刚创建)交流