Created
December 7, 2020 20:03
-
-
Save mjmdavis/c89f343f0fb6bb9224d93cbc45657a97 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests | |
from datetime import date | |
from bs4 import BeautifulSoup | |
from IPython import display | |
cookies_s = “””the cookies your browser sends to AoC””” | |
class AoC: | |
base_url = "https://adventofcode.com/" | |
def __init__(self, cookies_string): | |
self.make_session(cookies_string) | |
def make_session(self, cookies_string): | |
self.session = requests.Session() | |
cookie_dict = parse_cookie_string(cookies_string) | |
requests.utils.add_dict_to_cookiejar(self.session.cookies, cookie_dict) | |
def get_year(self): | |
today = date.today() | |
if today.month < 12: | |
return today.year - 1 | |
else: | |
return today.year | |
def get(self, url): | |
r = self.session.get(url) | |
assert r.status_code == 200, f"Failed get request with status code: {r.status_code}, message: {r.content}" | |
return r | |
def get_day_problem(self, year=None, day=1): | |
if year is None: | |
year = self.get_year() | |
url = self.base_url + f"{year}/day/{day}" | |
r = self.get(url) | |
problem_html = self.get_problem_from_content(r.content) | |
html_display = display.HTML(problem_html) | |
return html_display | |
def get_problem_from_content(self, content): | |
soup = BeautifulSoup(content, features="html.parser") | |
main = soup.find('main') | |
return str(main) | |
def get_input_data(self, year=None, day=1): | |
if year is None: | |
year = self.get_year() | |
url = self.base_url + f"{year}/day/{day}/input" | |
r = self.get(url) | |
return r.content.decode('utf-8') | |
def parse_cookie_string(cookie_string): | |
cookies_lines = cookie_string.split('\n') | |
cookies = {key:value for key, value in [line.split('=') for line in cookies_lines]} | |
return cookies |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment