#!/usr/bin/env python
#-*-coding:utf-8-*-
import sys
import urllib, urllib2
import cookielib
import getpass
from bs4 import BeautifulSoup
home_url = 'http://acm.sdut.edu.cn/onlinejudge2/index.php/Home'
login_url = 'http://acm.sdut.edu.cn/onlinejudge2/index.php/Home/Login/login'
#安装cookie处理
cookie_support = urllib2.HTTPCookieProcessor(cookielib.CookieJar())
opener = urllib2.build_opener(cookie_support)
urllib2.install_opener(opener)
#初始化cookie
home_temp = urllib2.urlopen(home_url)
#伪装成goole浏览器,以免服务器拒绝访问
headers = {'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36'}
uername = raw_input('请输入用户名')
key = getpass.getpass('请输入登录密码') #密码不可见
values = {'user_name': uername, 'password': key}
#login
post = urllib.urlencode(values)
request = urllib2.Request(login_url, post, headers)
response = urllib2.urlopen(request)
html = response.read()
#解析登录后的页面并判断是否登录成功
soup = BeautifulSoup(html, 'lxml')
if soup.find(text = 'Logout') != None:
print '登录成功!'
else:
print '登录失败!'
sys.exit(0) #直接退出
#找到个人信息页面
info_url = 'http://acm.sdut.edu.cn' + soup.find(class_ = 'nav navbar-nav navbar-right').li.a['href']
html = urllib2.urlopen(info_url)
info = BeautifulSoup(html, 'lxml')
#然后就可以搞事情啦~获取你想要的信息,比如这里我们获取用户AC的题目
temp = str(info.find_all(class_ = 'inner problem_list')[1])
temp = temp[33:-7]
t = temp.split('</a>')
problem = []
for i in range(len(t)-1):
string = str(t[i])
problem.append(string[-4:])
problem.sort()
print problem
print '总共%d个'% len(problem)
放一张运行截图吧