Parsen vom Daten aus Script
Verfasst: Montag 9. Dezember 2019, 14:40
Hey,
ich Versuche Daten von Lieferando zu Crawlen, das hat auch alles funktioniert, bis Lieferando ihren HTML Code geändert hat und die PLZ nicht mehr direkt auslesbar ist. Allerdings habe ich im Code folgende Struktur gefunden:
Musste hier leider ein Bild nehmen, da es sonst zu viele Zeichen sind.
https://www.bilder-upload.eu/bild-fb904 ... 5.jpg.html
Dort sind die Geo-Coordinaten drin aufgeführt, diese hätte ich gerne irgendwie da ausgelesen, ich weiß nur nicht wie. Anfangs habe ich angedacht beim Komma zu splitten.Die Anzahl Variert aber zu stark, hat da jemand eine Idee?
Also am besten wäre ein Dictionary mit allen IDS und den dazugehörigen Geo-Koordinaten.
Die Zuordnung geht über die Restaurant ID, welche ich für jedes Restaurant schon mit im Dict gespeichert habe, aber wie füge ich anhand dieser ID die richtigen Geo-Koordinaten zu dem richtigen Eintrag zu?
Hier mal mein kompletter Code bis jetzt:
ich Versuche Daten von Lieferando zu Crawlen, das hat auch alles funktioniert, bis Lieferando ihren HTML Code geändert hat und die PLZ nicht mehr direkt auslesbar ist. Allerdings habe ich im Code folgende Struktur gefunden:
Musste hier leider ein Bild nehmen, da es sonst zu viele Zeichen sind.
https://www.bilder-upload.eu/bild-fb904 ... 5.jpg.html
Dort sind die Geo-Coordinaten drin aufgeführt, diese hätte ich gerne irgendwie da ausgelesen, ich weiß nur nicht wie. Anfangs habe ich angedacht beim Komma zu splitten.Die Anzahl Variert aber zu stark, hat da jemand eine Idee?
Also am besten wäre ein Dictionary mit allen IDS und den dazugehörigen Geo-Koordinaten.
Die Zuordnung geht über die Restaurant ID, welche ich für jedes Restaurant schon mit im Dict gespeichert habe, aber wie füge ich anhand dieser ID die richtigen Geo-Koordinaten zu dem richtigen Eintrag zu?
Hier mal mein kompletter Code bis jetzt:
Code: Alles auswählen
from bs4 import BeautifulSoup
import requests
HEADERS = {"User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:44.0) Gecko/20100101 Firefox/44.0"}
def get_cityname_from_postcode(postcode):
try:
url = f"https://www.google.com/search?q={postcode}"
page = requests.get(url, headers=HEADERS)
soup = BeautifulSoup(page.content, "html.parser")
cityname = soup.find('span',{'class':"LrzXr kno-fv"}).find('a',{'class':'fl'}).get_text()
return cityname
except AttributeError:
return None
def show_results(restaurants_with_information):
for key in restaurants_with_information.keys():
print(f"Name: {key}")
print(f"Adresse: {restaurants_with_information[key]['Adress']}")
print(f"Essen: {restaurants_with_information[key]['Food']}")
print(f"Bewertung: {restaurants_with_information[key]['Rating']}" if restaurants_with_information[key]['Rating'] == "Keine Angaben" else f"Bewertung: {restaurants_with_information[key]['Rating']}/5")
print(f"Lieferkosten: {restaurants_with_information[key]['Delivery cost']}")
print(f"Bestellwert: {restaurants_with_information[key]['Min order']}")
print(f"Geöffnet ab: {restaurants_with_information[key]['Open time']}")
print(f"Restaurant ID: {restaurants_with_information[key]['Restaurant ID']}\n")
print(f"Es wurden {len(restaurants_with_information)} Restaurants gefunden\n")
def save_results_in_file(restaurants_with_information):
output_filename = "Lieferando_output.txt"
with open(output_filename, 'w', encoding="UTF-8") as outputfile:
for key in restaurants_with_information.keys():
outputfile.write(f"Name: {key}\n")
outputfile.write(f"Adresse: {restaurants_with_information[key]['Adress']}\n")
outputfile.write(f"Essen: {restaurants_with_information[key]['Food']}\n")
outputfile.write(f"Bewertung: {restaurants_with_information[key]['Rating']}\n" if restaurants_with_information[key]['Rating'] == "Keine Angaben" else f"Bewertung: {restaurants_with_information[key]['Rating']}/5\n")
outputfile.write(f"Lieferkosten: {restaurants_with_information[key]['Delivery cost']}\n")
outputfile.write(f"Bestellwert: {restaurants_with_information[key]['Min order']}\n")
outputfile.write(f"Geöffnet ab: {restaurants_with_information[key]['Open time']}\n")
outputfile.write(f"Restaurant ID: {restaurants_with_information[key]['Restaurant ID']}\n\n")
print(f"Ergebnisse wurden in {output_filename} gespeichert.\n")
def fill_dictionary(restaurants):
restaurants_with_information = {}
for restaurant in restaurants[:-1]:
restaurant_name = get_restaurant_name(restaurant)
restaurant_adress = get_restaurant_adress(restaurant)
restaurant_food = get_restaurant_food(restaurant)
restaurant_rating = get_restaurant_rating(restaurant)
delivery_cost = get_delivery_cost(restaurant)
minimal_order_value = get_minimal_order_value(restaurant)
open_time = get_open_time(restaurant)
restaurant_id = get_restaurant_id(restaurant)
restaurants_with_information[restaurant_name] = {"Adress":restaurant_adress, "Food":restaurant_food, "Rating":restaurant_rating, "Delivery cost": delivery_cost, "Min order": minimal_order_value, "Open time":open_time, "Restaurant ID":restaurant_id}
return restaurants_with_information
def get_restaurant_rating(restaurant):
rating_block = restaurant.find(itemtype='http://schema.org/Rating')
if rating_block.find(itemprop='reviewCount').get('content') != "0":
rating = rating_block.find(itemprop='ratingValue').get('content')
else:
rating = "Keine Angaben"
return rating
def get_restaurant_name(restaurant):
try:
restaurant_name = restaurant.find('a', {'class':'restaurantname'}).get_text().strip()
except AttributeError:
restaurant_name = "Fehler"
return restaurant_name
def get_restaurant_adress(restaurant):
try:
restaurant_adress = restaurant.find('div', {'class':'address'}).get_text().strip()
except AttributeError:
restaurant_adress = "Keine Angaben"
return restaurant_adress
def get_restaurant_food(restaurant):
try:
restaurant_food = restaurant.find('div',{'class':'kitchens'}).get_text().strip()
except AttributeError:
restaurant_food = "Keine Angaben"
return restaurant_food
def get_delivery_cost(restaurant):
try:
delivery_cost = restaurant.find('div',{'class':'delivery-cost js-delivery-cost'}).get_text().strip()
except AttributeError:
delivery_cost = "Keine Angaben"
return delivery_cost
def get_minimal_order_value(restaurant):
try:
minimal_order_value = restaurant.find('div',{'class':'min-order'}).get_text().strip()
except AttributeError:
minimal_order_value = "Keine Angaben"
return minimal_order_value
def get_open_time(restaurant):
try:
open_time = restaurant.find('div',{'class':'avgdeliverytime avgdeliverytimefull open'}).get_text().strip()
except AttributeError:
open_time = "Keine Angaben"
return open_time
def get_restaurant_id(restaurant):
try:
restaurant_id = restaurant.get("id").replace("irestaurant", "")
except AttributeError:
restaurant_id = "Keine Angaben"
return restaurant_id
def make_urls(postcode, cityname):
return [f"https://www.lieferando.de/lieferservice-{cityname}-{postcode}", f"https://www.lieferando.de/lieferservice-{postcode}"]
def cityname_without_umlaut(cityname):
chars = {'ö':'oe','ä':'ae','ü':'ue'}
if cityname != None:
if any(char in cityname for char in chars.keys()):
for char in chars:
cityname = cityname.replace(char,chars[char])
return cityname
def get_restaurantlist(url):
page = requests.get(url, headers=HEADERS)
soup = BeautifulSoup(page.content, "html.parser")
all_restaurant_infoboxes = soup.find('div',id = 'irestaurantlist')
return all_restaurant_infoboxes
def main():
postcode = input("Bitte gib deine Postleitzahl ein: ")
print("Bitte warte einige Sekunden...\n")
cityname = cityname_without_umlaut(get_cityname_from_postcode(postcode))
url = make_urls(postcode, cityname)[1]
all_restaurant_infoboxes = get_restaurantlist(url)
if all_restaurant_infoboxes == None:
url = make_urls(postcode, cityname)[0]
all_restaurant_infoboxes = get_restaurantlist(url)
restaurants = all_restaurant_infoboxes.find_all(itemtype="http://schema.org/Restaurant")
result = fill_dictionary(restaurants)
show_results(result)
save_results = True if input("Willst du die Ergebnisse in einer Textdatei speichern? (Y/N): ") == "Y" else False
if save_results:
save_results_in_file(result)
print("Programmende")
if __name__ == "__main__":
main()