Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
import os
import re
from getpass import getpass
from requests import Session
STATUS_PAGE = "http://www.spoj.com/status/{problem},{username}/"
MYACCOUNT_PAGE = "http://www.spoj.com/myaccount/"
SOLUTION_PAGE = "http://www.spoj.com/files/src/save/{sol_id}"
HOME_PAGE = "https://www.spoj.com/"
class Login(object):
def __init__(self, username, password):
self.session = Session()
self.username = username
self.password = password
def __enter__(self):
self.session.post(HOME_PAGE, data={
'login_user': self.username,
'password': self.password
})
return self.session
def __exit__(self, _1, _2, _3):
return False
class TakeDirectory(object):
def __init__(self, path):
self.oldloc = os.path.abspath(os.curdir)
self.newloc = path
def __enter__(self):
if not os.path.exists(self.newloc):
os.mkdir(self.newloc)
if not os.path.isdir(self.newloc):
raise RuntimeError
os.chdir(self.newloc)
def __exit__(self, _1, _2, _3):
os.chdir(self.oldloc)
return False
def getSolvedProblems(doc, username):
pattern = '/status/(.{3,8}),' + username + '/'
return re.findall(pattern, doc)
def getSolutions(doc):
pattern = '/files/src/([0-9]*?)/'
return re.findall(pattern, doc)
def download():
username = raw_input("username: ")
password = getpass("password: ")
with Login(username, password) as session:
for prob_id in getSolvedProblems(session.get(MYACCOUNT_PAGE).content, username):
with TakeDirectory(os.path.abspath(prob_id)):
for sol_id in getSolutions(session.get(
STATUS_PAGE.format(problem=prob_id, username=username)).content):
with open(sol_id, 'w') as solution:
solution.write(session.get(SOLUTION_PAGE.format(sol_id=sol_id)).content)
if __name__ == '__main__':
download()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment