KS想看自己在TOJ上提交的但是没AC的题目 ,但是又不想一页一页的翻 ; 正好这几天才学了pyhon ,就想写个爬虫程序,才爬取;需要输入toj的账号密码信息,用的还是前面介绍的,TOJ涉及到了登录, 可以通过审查元素来查看,需要什么信息, 还好TOJ的加密没有QQ空间那么高(e)端(xin)=== 直接按正常步骤就可以登录 ,下面就是对页面的解析了;与一般页面不同的是, TOJ把user对题目的state 存在js里面了,因此后面用到的是解析字符串,而非html, 简单一些了
贴图:
代码如下:(PS: 写的不完善,登录失败会没有信息输出)
# -*- coding: cp936 -*-
import urllib2,urllib,cookielib,time,os,sys
from bs4 import BeautifulSoup
class Problem:
def __init__(self,state,id,name):
self.id=id
self.state=state
self.name=name
#cookie
cookiejar= cookielib.CookieJar()
cookieproc= urllib2.HTTPCookieProcessor(cookiejar)
opener= urllib2.build_opener(cookieproc)
urllib2.install_opener(opener)
do_wa=[]#save unac problems
url='http://acm.tju.edu.cn/toj/list.php?vol='
username=raw_input('input your id for TOJ:')
password=raw_input('input your password:')
domain='acm.tju.edu.cn'
##handle
def handle(str):
index=str.index('}')
str=str[index+2:-10]
p_list=str.split('\n')
for p in p_list:
list_do=p.split(',')
if list_do[1]=='2':
do_wa.append(Problem(list_do[1],list_do[2],list_do[3]))
#headers and postdata for broswers
headers={
'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:30.0) Gecko/20100101 Firefox/30.0'
}
postdata={
'user_id':username,\
'passwd':password,
'domain':domain,
'login':'Login'
}
postdata=urllib.urlencode(postdata)
#handle
print username,'do but un_ac:'
for i in range(1,100):
#time.sleep(0.1)
toj_url=url+str(i)
req=urllib2.Request(toj_url,postdata)
html=urllib2.urlopen(req).read()
html= BeautifulSoup(html)
script=html.find('script')
script=str(script)
if script=='None':
break
handle(script)
for i in do_wa :
print i.id,i.name
os.system('pause')