1
Fork 0

Grote push

This commit is contained in:
Tibo De Peuter 2022-05-19 15:43:18 +02:00
parent 4bcf82fa3e
commit 847f6650e9
7 changed files with 175 additions and 42 deletions

View file

@ -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')
'MedchalMalkajgiri district'
>>> converteer('MedchalMalkajgiri 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 <p> 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', 'MedchalMalkajgiri 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}