Tags: beautifulsoup requests
Rating:
```
import requests
import json
from bs4 import BeautifulSoup as bs4
################################################################################
#
# Stage 1:
#
# Request a session for the first "round", in this, we'll submit a lot of wrong
# answers and store the resulting solution given to us by the server. The plan
# is to use this solutions in a second round to solve the questions
#
########################################
# question_mapping maps the question to it's answer
# load the stored data
question_mapping = {}
with open("solutions.json") as data:
question_mapping = json.load(data)
s1 = requests.Session()
s1.close()
s1 = requests.Session()
#for i in range(0, 2000):
i=0
while len(question_mapping) < 1000:
print(f"\r{i}\t{len(question_mapping)}", end="", flush=True)
r = s1.get("http://timesink.be/quizbot/index.php")
soup = bs4(r.text, "html.parser")
question = soup.h4.text
# post with body:
payload = {"insert_answer": "asdfghjkl", "submit": "answer"}
r = s1.post("http://timesink.be/quizbot/index.php", data=payload)
soup = bs4(r.text, "html.parser")
answer = soup.find(id="answer").text
question_mapping[question] = answer
i+=1
# save the dict to json
with open("solutions.json", "w") as outfile:
json.dump(question_mapping, outfile)
print("")
################################################################################
#
# Stage 2:
#
# Use the solutions collected in stage 1
#
########################################
s2 = requests.Session()
for i in range(0, 1100):
try:
r = s1.get("http://timesink.be/quizbot/index.php", timeout=10)
soup = bs4(r.text, "html.parser")
question = soup.h4.text
try:
answer = question_mapping[question]
except:
answer = "abc"
print(question)
print(answer)
except:
print("SOME ERROR OCCURED")
try:
# post with body:
payload = {"insert_answer": answer, "submit": "answer"}
r = s1.post("http://timesink.be/quizbot/index.php", data=payload, timeout=10)
soup = bs4(r.text, "html.parser")
print(r.text)
#answer = soup.find(id="answer").text
except:
print("SOME ERROR OCCURED")
```