diff --git a/cgi-bin/init.py b/cgi-bin/init.py index 499560c..ae521a3 100644 --- a/cgi-bin/init.py +++ b/cgi-bin/init.py @@ -9,11 +9,11 @@ De bestandsextensie werd aangepast om te kunnen debuggen op zowel Windows als Li import cgi import json -from scraper import run, converteer +from scraper import run parameters = cgi.FieldStorage() data = json.loads(parameters.getvalue('data')) -antwoord = run(data['taal'], converteer(data['start']), converteer(data['einde'])) +antwoord = run(data['taal'], data['start'], data['einde']) print("Content-Type: application/json") print() # Lege lijn na headers diff --git a/cgi-bin/scraper.py b/cgi-bin/scraper.py index 0ba0bb0..b31fc0a 100644 --- a/cgi-bin/scraper.py +++ b/cgi-bin/scraper.py @@ -9,11 +9,24 @@ from bs4 import BeautifulSoup import requests -def converteer(tekst, user=True): - if user: - return tekst.replace(' ', '_') +def converteer(tekst, gebruiker=True): + """ + >>> converteer('Northwestern Europe') + 'Northwestern Europe' + >>> converteer('Northwestern_Europe', False) + 'Northwestern_Europe' + >>> converteer('Medchal%E2%80%93Malkajgiri_district') + 'Medchal–Malkajgiri district' + >>> converteer('Medchal–Malkajgiri district', False) + 'Medchal%E2%80%93Malkajgiri_district' + """ + + from urllib import parse + + if gebruiker: + return parse.unquote(tekst).replace('_', ' ').split('#')[0] else: - return tekst.replace('_', ' ') + return parse.quote(tekst.replace(' ', '_')) def zoek_link(soep): @@ -31,10 +44,19 @@ def zoek_link(soep): 'High-level_programming_language' >>> zoek_link(BeautifulSoup(requests.get('https://en.wikipedia.org/wiki/Department_of_Standards_Malaysia').content, 'html.parser')) 'Ministry_of_International_Trade_and_Industry_(Malaysia)' - """ - # TODO Zorg ervoor dat tekst schuin of vetjes ook nog herkend wordt + >>> zoek_link(BeautifulSoup(requests.get('https://en.wikipedia.org/wiki/Malawi').content, 'html.parser')) + 'Tumbuka_language' - lijsttypes = ['ul', 'ol'] # Lijsttypes die we kunnen gebruiken + Maar eventueel als alternatief 'Landlocked_country' ?? + >>> zoek_link(BeautifulSoup(requests.get('https://en.wikipedia.org/wiki/%27s-Gravenweg_168,_Kralingen').content, 'html.parser')) + 'Kralingen' + """ + + # Ik heb besloten om ook lijsttypes te kunnen doorzoeken op nuttige linkjes. Dit is strikt genomen tegen de + # beschrijving van de opgave, maar volgens https://en.wikipedia.org/wiki/Wikipedia:Getting_to_Philosophy lijkt dit + # de logische methode, dus ik besloot ook lijsten te ondersteunen, als extra uitdaging. Ik vermoedde dat de opgave + # van het project eerder
specifieerde om ons wat hoofdbreuk te besparen. + ondersteuning = ['p', 'ul', 'ol'] link = None # Navigeer naar het niveau op de pagina waarop we zullen zoeken. @@ -43,7 +65,7 @@ def zoek_link(soep): # Niet recursief zoeken om niet in een tabel of iets dergelijke vast te komen. # Het niveau onder 'mw-parser-output' is wat we nodig hebben en waar alle nodige alinea's in staan. - alinea = soep.find(['p', lijsttypes], recursive=False) + alinea = soep.find(ondersteuning, recursive=False) # Ga steeds verder omlaag (niet dieper) totdat er een geldige link is gevonden. while link is None: @@ -52,9 +74,10 @@ def zoek_link(soep): # Negeer linkjes in superscript, dus zoek enkel op het huidige niveau. potentieel = alinea.find('a') + # Spans negeren is redelijk enkel en alleen om coördinaat stukjes te vermijden. while potentieel is None or alinea.findChild().name == 'span': - alinea = alinea.findNextSibling(['p', lijsttypes]) + alinea = alinea.findNextSibling(ondersteuning) # Het zou kunnen dat de bewerking hierboven ervoor zorgt dat we op het einde van de pagina zijn if alinea is None: @@ -110,42 +133,52 @@ def run(taal, start, stop): >>> run('en', "Belgium", "Philosophy") {'pad': ['Belgium', 'Northwestern Europe', 'Subregion', 'Region', 'Geography', 'Science', 'Scientific method', 'Empirical evidence', 'Proposition', 'Logic', 'Reason', 'Consciousness', 'Sentience', 'Emotion', 'Mental state', 'Mind', 'Phenomenon', 'Immanuel Kant', 'Philosophy']} >>> run('en', 'Department of Standards Malaysia', 'Philosophy') - {'pad': ['Department_of_Standards_Malaysia', 'Ministry of International Trade and Industry (Malaysia)', 'Ministry (government department)', 'Executive (government)', 'Government', 'State (polity)', 'Germans', 'Germany', 'Central Europe', 'Europe', 'Continent', 'Landmass', 'Region', 'Geography', 'Science', 'Scientific method', 'Empirical evidence', 'Proposition', 'Logic', 'Reason', 'Consciousness', 'Sentience', 'Emotion', 'Mental state', 'Mind', 'Phenomenon', 'Immanuel Kant', 'Philosophy']} + {'pad': ['Department of Standards Malaysia', 'Ministry of International Trade and Industry (Malaysia)', 'Ministry (government department)', 'Executive (government)', 'Government', 'State (polity)', 'Germans', 'Germany', 'Central Europe', 'Europe', 'Continent', 'Landmass', 'Region', 'Geography', 'Science', 'Scientific method', 'Empirical evidence', 'Proposition', 'Logic', 'Reason', 'Consciousness', 'Sentience', 'Emotion', 'Mental state', 'Mind', 'Phenomenon', 'Immanuel Kant', 'Philosophy']} >>> run('en', 'Malkajgiri mandal', 'Philosophy') - {'pad': ['Malkajgiri_mandal', 'Medchal%E2%80%93Malkajgiri district', 'District', 'Administrative division', 'Sovereign state', 'Polity', 'Politics', 'Decision-making', 'Psychology', 'Science', 'Scientific method', 'Empirical evidence', 'Proposition', 'Logic', 'Reason', 'Consciousness', 'Sentience', 'Emotion', 'Mental state', 'Mind', 'Phenomenon', 'Immanuel Kant', 'Philosophy']} + {'pad': ['Malkajgiri mandal', 'Medchal–Malkajgiri district', 'District', 'Administrative division', 'Sovereign state', 'Polity', 'Politics', 'Decision-making', 'Psychology', 'Science', 'Scientific method', 'Empirical evidence', 'Proposition', 'Logic', 'Reason', 'Consciousness', 'Sentience', 'Emotion', 'Mental state', 'Mind', 'Phenomenon', 'Immanuel Kant', 'Philosophy']} Loops >>> run('nl', 'België', 'Philosophy') + {'error': "Cyclus gedetecteerd op 'Wetenschap', het onafgewerkte pad zal niet worden toegevoegd aan het overzicht."} + >>> run('en', 'Tom Inglesby', 'Contract failure') + {'pad': ['Tom Inglesby', 'Johns Hopkins Center for Health Security', 'Nonprofit organization', 'Contract failure']} Doodlopende eindes + TODO Voorbeelden zoeken + + Foute linkjes + >>> run('en', 'Deze pagina bestaat niet', 'Philosophy') + {'error': "Er ging iets fout bij het inladen van 'Deze pagina bestaat niet'. Bestaat de website?"} """ # Negeer de 'random' waarde als er op deze manier gestart wordt. - lijst = [converteer(start)] if start != 'Special:Random' else [] + lijst = [converteer(start, True)] if start != 'Special:Random' else [] base = f"https://{taal}.wikipedia.org/wiki/" while start != stop: + # Pagina inladen. - pagina = requests.get(base + start) + pagina = requests.get(base + converteer(start, False)) + + # Stoppen indien het inladen van de pagina niet lukte. + if pagina.status_code != 200: + return {'error': f"Er ging iets fout bij het inladen van '{lijst[-1]}'. Bestaat de website?"} # Verwerken. soep = BeautifulSoup(pagina.content, 'html.parser') # Volgende link zoeken. - start = zoek_link(soep) + start = converteer(zoek_link(soep)) - # TODO Dit verder uitwerken if start is None: - return {'error': f'Er konden geen nieuwe links meer gevonden worden op {lijst[-1]}'} + return {'error': f"Er konden geen nieuwe links meer gevonden worden op '{lijst[-1]}'"} # Cyclus detecteren - nieuw = converteer(start.split('/')[-1], False) - if nieuw in lijst: - return { - 'error': - f'Cyclus gedetecteerd op {nieuw}, het onafgewerkte pad zal niet worden toegevoegd aan het overzicht' - } + if start in lijst: + return {'error': + f"Cyclus gedetecteerd op '{start}', startende vanaf '{lijst[0]}'. Het onafgewerkte pad zal niet worden toegevoegd aan het overzicht. " + } - lijst.append(nieuw) + lijst.append(start) return {'pad': lijst} diff --git a/cgi-bin/stresstest.py b/cgi-bin/stresstest.py new file mode 100644 index 0000000..5449bf8 --- /dev/null +++ b/cgi-bin/stresstest.py @@ -0,0 +1,41 @@ +#!/usr/bin/env python3 + +""" +Dit script is enkel en alleen bedoeld om heel veel willekeurige pagina's te kunnen testen en +enkel degene eruit te halen die falen (en dus niet correct afgehandeld worden). +""" + +from bs4 import BeautifulSoup +import requests + +from scraper import converteer, zoek_link + + +def run(taal, start, stop): + lijst = [converteer(start, True)] if start != 'Special:Random' else [] + base = f"https://{taal}.wikipedia.org/wiki/" + + while start != stop: + + # Dit is het enigste dat we aanpassen. + print(lijst[-1] if len(lijst) != 0 else []) + + pagina = requests.get(base + converteer(start, False)) + if pagina.status_code != 200: + return {'error': f"Er ging iets fout bij het inladen van '{lijst[-1]}'. Bestaat de website?"} + soep = BeautifulSoup(pagina.content, 'html.parser') + start = converteer(zoek_link(soep)) + if start is None: + return {'error': f"Er konden geen nieuwe links meer gevonden worden op '{lijst[-1]}'"} + if start in lijst: + return {'error': + f"Cyclus gedetecteerd op '{start}', startende vanaf '{lijst[0]}'. Het onafgewerkte pad zal niet worden toegevoegd aan het overzicht. " + } + lijst.append(start) + return {'pad': lijst} + + +antwoord = run('en', 'Special:Random', 'Philosophy') +while 'pad' in antwoord or antwoord['error'].startswith('Cyclus'): + antwoord = run('en', 'Special:Random', 'Philosophy') +print(antwoord['error']) diff --git a/images/wikipedia_edit.png b/images/wikipedia_edit.png new file mode 100644 index 0000000..fbe80ed Binary files /dev/null and b/images/wikipedia_edit.png differ diff --git a/index.html b/index.html index e3db1f0..3897b27 100644 --- a/index.html +++ b/index.html @@ -2,20 +2,27 @@
-+ De huidige boom zal overschreven worden bij een nieuwe toevoeging. +