[python] HDU自动登录提交代码程序

时间:2021-02-18 22:09:32

调了一个下午,被python的正则绊住了;在C#上运作好好的式子在python老是报错,原来python的断言式必须是固定长度的,像类似(?<=[^>].*?)的零宽度正回顾后发断言是不允许出现的,这点python做的没有C# 方便,弄得我只好分了好几个步骤来做.

[python] HDU自动登录提交代码程序

 __author__ = 'wuminye'
import time
import urllib
import urllib2
import cookielib
import re std = ['Queuing', 'Compiling', 'Running'] hostaddr = 'http://acm.hdu.edu.cn'
loginaddr = '/userloginex.php?action=login'
submaddr = '/submit.php?action=submit'
statusaddr = '/status.php' cj = cookielib.LWPCookieJar()
cookie_support = urllib2.HTTPCookieProcessor(cj)
#httpHandler = urllib2.HTTPHandler(debuglevel=1)
opener = urllib2.build_opener(cookie_support, urllib2.HTTPHandler)
urllib2.install_opener(opener)
header = {'User-Agent': 'IE10'} def login(username, password):
""" :rtype : object
"""
postData = {'username': username,
'userpass': password,
'submit': 'Sign In'}
postData = urllib.urlencode(postData)
request = urllib2.Request(hostaddr + loginaddr, postData, header)
response = urllib2.urlopen(request, timeout=10)
if response.getcode() != 200 and response.getcode() != 302:
print 'login web error!'
return False
ans = response.read()
if ans.find("Sign Out") == -1:
return False
return True def querystatus():
postData = {'user': 'wuminye',
'lang': 0,
'first': '',
'pid': '',
'status': 0}
postData = urllib.urlencode(postData)
request = urllib2.Request(hostaddr + statusaddr + '?' + postData, headers=header)
response = urllib2.urlopen(request, timeout=10)
if response.getcode() != 200 and response.getcode() != 302:
print 'query web error!'
return False
ans = response.read()
m = re.search('(?<=<td height=22px>).*?</td>(<td.*?</td>){8}(?=</tr>)', ans)
ans = '<td>' + m.group(0)
mylist = []
for i in range(0, 7):
m = re.search(r"(?<=<td).+?(?=</td>)", ans)
t = m.group()[1:]
n = t.find('>')
if n != -1:
t = t[n + 1:]
t = re.search('[^<]+', t)
mylist.append(t.group())
ans = ans[m.end() + 5:]
for i in range(0, 4):
ans = ans[ans.find('>') + 1:]
ans = re.search(r"[^<]+", ans).group()
mylist.append(ans)
return mylist def subbmit(pid, lan, code):
postData = {'problemid': pid,
'language': lan,
'usercode': code,
'submit': 'Submit'}
postData = urllib.urlencode(postData)
request = urllib2.Request(hostaddr + submaddr, postData, header)
response = urllib2.urlopen(request, timeout=10)
if response.getcode() != 200 and response.getcode() != 302:
print 'subbmit web error!'
return False
print 'Subbmit Done!'
ans = querystatus()
while ans[2] in std:
time.sleep(1)
print 'Status:', ans[2]
ans = querystatus()
print ans