BGround
抓网页什么的已经很熟♂练♂了,想要搞一搞模拟登陆了
正题之前
以前一直都是用urllib2的urlopen().read()开网页的,但是经常性的有UrlError这种神奇的错误(字面意思),搜了很久问了很久就找到了requests
调用的方法大概是
import requests
response = requests.get(url, headers = headers)
print requests.content
速度不知道,但是蛋疼的错误没了
目标
我们的目标是——
刷!爆!题!库!
是的,想要码一个程序通过登录学校题库的帐号然后提交所有题目并超时
正题
首先要清楚,在提交题目之前,我们需要登录题库
在html中,登录的请求实际上就是一个post,这个post里面包含了必须的用户id、密码或者是邮箱
那么如何查看这个post呢?
在浏览器中打开页面,然后按F12(win下),会出现
输入帐号和密码点击登录/login/sign in
还有这个
划红线的东西就是需要的data了,打个dict就能post出去
data = {'user_id1': userId, 'password1': password, 'B1': 'login'}
html.post(loginUrl, data = data)
return html
提交也类似,不讲了。有兴趣可以自己想想或者问我也行的(不拒绝评论和私信还有赞的)
Code
import requests
import time
import re
def logIn(html, loginUrl, userId, password):
data = {'user_id1': userId, 'password1': password, 'B1': 'login'}
html.post(loginUrl, data = data)
return html
def submitProb(html, submitUrl, probId, source):
data = {'problem_id': probId, 'language': 2, 'source': source, 'submit': 'Submit'}
try:
html.post(submitUrl, data = data)
except Exception, e:
submitProb(html, submitUrl, probId, source)
def getStatusList(statusPage):
statusReg = re.compile(r'<tr align=center><td>.+?</td><td><a href=.+?>(.+?)</a></td><td><a href=.+?>(.+?)</a></td><td><font color=.+?>.+?</font></td><td>.+?</td><td>.+?</td><td>(.+?)</td><td>.+?</td><td>.+?</td></tr>')
statusList = re.findall(statusReg, statusPage)
return statusList
def getPage(html, url):
headers = {'User-Agent': 'Mozilla/5.0 (compatible; MSIE 5.5; Windows NT)'}
try:
response = html.get(url, headers = headers, timeout = 2)
page = response.content
return page
except Exception, e:
page = getPage(html, url)
return page
loginUrl = 'http://10.156.17.250/JudgeOnline/login?action=login'
submitUrl = 'http://10.156.17.250/JudgeOnline/submit'
statusUrl = 'http://10.156.17.250/JudgeOnline/status'
source = '''
var a,b,i:longint;
begin
readln(a);
for i:=1 to 1000000000 do
a:=a+1-1;
writeln(a+b);
end.
'''
userId = 'lylovely'
password = '66666666'
html = requests.Session()
statusHtml = requests.Session()
logIn(html, loginUrl, userId, password)
for index in range(1400,2625,1):
submitProb(html, submitUrl, index, source)
statusPage = getPage(statusHtml, statusUrl)
statusList = getStatusList(statusPage)
status = statusList[0]
print index
time.sleep(3)