119 lines
5.2 KiB
Python
119 lines
5.2 KiB
Python
from sys import argv
|
|
from os import environ
|
|
from dotenv import load_dotenv
|
|
from cloudscraper import CloudScraper, create_scraper
|
|
from re import findall
|
|
|
|
class Scraper:
|
|
def __init__(self, pseudo, password, app, debug = False):
|
|
self.debug = debug
|
|
self.url = "https://forum.mobilism.org"
|
|
self.requested_app = app
|
|
self.loginData = {
|
|
"username": pseudo,
|
|
"password": password,
|
|
"login": "Login"
|
|
}
|
|
|
|
def errorFormat(self, code: int = None, message: str = "") -> str:
|
|
"""Pretty error message."""
|
|
return f"{f'[{code}]' if code else ''}{' ' if len(message) > 0 and code else ''}{message}."
|
|
|
|
def connect(self) -> CloudScraper:
|
|
"""Login to the forum using credentials."""
|
|
session = create_scraper(browser = {"browser": "chrome", "platform": "windows"}) # connect with cloudflare bypasser with a chrome browser on windows
|
|
if not session:
|
|
raise SystemError(self.errorFormat(message = "The creation of the session failed")) # called only if failed at creating the session
|
|
|
|
if self.debug: print("Connection attempt...")
|
|
reponse = session.post(f"{self.url}/ucp.php", data = self.loginData, params = {"mode": "login"}) # connect to the forum using credentials - params are set by default but its in case forum changing that
|
|
if reponse.status_code != 200:
|
|
raise ConnectionRefusedError(self.errorFormat(code = reponse.status_code, message = "Unable to connect")) # called only status code isn't 200
|
|
|
|
return session
|
|
|
|
def search(self, session) -> list:
|
|
"""Do the research."""
|
|
if self.debug: print("Going to search page and check connection...", end = " ")
|
|
reponse = session.get(f"{self.url}/search.php", params = {"keywords": self.requested_app, "sr": "topics", "sf": "titleonly"}) # fetch results page
|
|
if "Sorry but you are not permitted to use the search system. If you're not logged in please" in reponse.text:
|
|
raise ConnectionError(self.errorFormat(message = "Connection failed, check credentials")) # called only if login failed
|
|
if reponse.status_code != 200:
|
|
raise ConnectionError(self.errorFormat(code = reponse.status_code, message = "Impossible to make the search")) # called only status code isn't 200
|
|
if self.debug: print(f"Connected.")
|
|
|
|
if self.debug: print(f"Fetching results for {self.requested_app}...", end = " ")
|
|
|
|
return self.parse(reponse.text)
|
|
|
|
def parse(self, htmlPage: str) -> list:
|
|
"""Parse HTML reponse to a clean list"""
|
|
if "No suitable matches were found." in htmlPage:
|
|
return []
|
|
elements = htmlPage.split("<tr>\n<td>")[1:]
|
|
elements[-1] = elements[-1].split("</td>\n</tr>")[0]
|
|
for i in range(0, len(elements)):
|
|
try:
|
|
_title = findall(r"class=\"topictitle\">(.*)<\/a>", elements[i])[0]
|
|
except:
|
|
_title = None
|
|
try:
|
|
_author = findall(r"<br />\n<i class=\"icon-user\"></i> by <a href=\"\./memberlist\.php\?mode=viewprofile&u=\d+\"( style=\"color: #.*;\" class=\"username-coloured\")?>(.*)</a>", elements[i])[0][-1]
|
|
except:
|
|
_author = None
|
|
try:
|
|
_link = findall(r"\./viewtopic\.php\?f=(\d*)&t=(\d*)&", elements[i])[0]
|
|
_link = {"f": _link[0], "t": _link[1]}
|
|
except:
|
|
_link = None
|
|
elements[i] = {"title": _title, "author": _author, "link": f"https://forum.mobilism.org/viewtopic.php?f={_link['f']}&t={_link['t']}", "linkParams": _link}
|
|
|
|
return elements
|
|
|
|
def work(self) -> str:
|
|
"""Call all the others methods."""
|
|
session = self.connect()
|
|
link = self.search(session)
|
|
|
|
return link
|
|
|
|
def save(elements):
|
|
"""Save all the results parsed to a CSV file."""
|
|
taille = len(elements)
|
|
if taille == 0:
|
|
print("Aucun élément n'a été trouvé avec la recherche.")
|
|
return
|
|
filename = "results.csv"
|
|
with open(filename, "w") as f:
|
|
f.write(";".join(list(elements[0].keys())[:-1]))
|
|
f.write("\n")
|
|
for element in elements:
|
|
if element != "linkParams":
|
|
f.write(";".join(str(e) for e in list(element.values())[:-1]))
|
|
f.write("\n")
|
|
print(f"{taille} éléments ont étés enrengistés dans le fichier {filename}.")
|
|
|
|
if __name__ == "__main__":
|
|
argv = argv[1:]
|
|
if len(argv) < 1:
|
|
print("No App to retrieve.")
|
|
exit(1)
|
|
load_dotenv()
|
|
try:
|
|
try:
|
|
debug = environ["DEBUG_MOBILISM"].lower() in ("yes", "true", "1")
|
|
except:
|
|
debug = False
|
|
try:
|
|
pseudoMobilism = environ["PSEUDO_MOBILISM"]
|
|
passwordMobilism = environ["PASSWORD_MOBILISM"]
|
|
except:
|
|
if len(argv) >= 3:
|
|
pseudoMobilism = argv[0]
|
|
passwordMobilism = argv[1]
|
|
argv = argv[-2:]
|
|
else:
|
|
raise KeyError
|
|
save(Scraper(pseudoMobilism, passwordMobilism, " ".join([n for n in argv]), debug).work())
|
|
except KeyError:
|
|
print('Please fill in the username and password (with quotes) by args or with .env file and give an app to retrieve.')
|