<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Peterfuhr on Medium]]></title>
        <description><![CDATA[Stories by Peterfuhr on Medium]]></description>
        <link>https://medium.com/@peterfuhr0?source=rss-ff57c0f7fcf8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*V3uBK_pohjKep-O9</url>
            <title>Stories by Peterfuhr on Medium</title>
            <link>https://medium.com/@peterfuhr0?source=rss-ff57c0f7fcf8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 23:50:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@peterfuhr0/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[A journey in Data-Engineering]]></title>
            <link>https://medium.com/@peterfuhr0/a-journey-in-data-engineering-417e9a55e70d?source=rss-ff57c0f7fcf8------2</link>
            <guid isPermaLink="false">https://medium.com/p/417e9a55e70d</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[web-scraping]]></category>
            <dc:creator><![CDATA[Peterfuhr]]></dc:creator>
            <pubDate>Thu, 11 Aug 2022 23:01:32 GMT</pubDate>
            <atom:updated>2022-08-12T10:09:58.883Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*Dt3DDpyC_UeIvqlombyeyQ.jpeg" /></figure><p>As a Data Scientist you usually get your Data from an Data Engineer. But usually means not always — and you won’t be able to rely on a Data Engineer being available in every company. So it is useful to have at least some basic knowledge in getting data by yourself.</p><p>This is why the objective in this project was focussed on classical Data Engineer tasks:</p><ul><li><strong>Data Collection:</strong> Collecting data via web scraping and APIs.</li><li><strong>Data Storage:</strong> Creating a database to upload the generated data.</li><li><strong>Cloud Automation:</strong> Creating pipelines in order to collect data on a regular basis</li></ul><p><strong>The Project:</strong></p><p>In the process of our DataScience Bootcamp be got the objective to gather data about cities, weather and flights for a fictive company called “Gans”, which wants to improve its placement of e-scooters. This was at least the initial approach. You’ll find the details about the data-gathering below.</p><p>I changed the scope of this project — maybe because of my own stupidity, because I made everything a lot harder. I realised, that e-scooters and airports don’t match at all. The typical distance for which an e-scooter is used is less than 2 km. The typical distance between a city-center and an airport is far greater (more than 20 km). So these figures didn’t add up. The typical usage of an e-scooter is in the city-center for small distances.</p><p>So I decided to look for websites which contain information about events. So “Gans” would be able to place their e-scooters at the right place at the right time.</p><p>But now, let’s head to the fun part: Data gathering.</p><h4>Data Gathering:</h4><p>Data Collecting is the first step to generate the Data Pipeline. There are different ways to gather needed data. I used tree different approaches to gather the needed data:</p><ul><li><a href="https://en.wikipedia.org/wiki/Web_scraping"><strong>Web Scraping:</strong></a> Extracting useful data from websites using <a href="https://pypi.org/project/requests/">Requests </a>and <a href="https://beautiful-soup-4.readthedocs.io/en/latest/">BeautifulSoup</a></li><li><a href="https://en.wikipedia.org/wiki/API"><strong>APIs:</strong></a><strong> </strong>Using defined interfaces to interact in order to extract data. You can find many APIs to different topics on <a href="https://rapidapi.com/hub">RapidAPI</a></li><li><strong>Files:</strong> There are many types of files which can help you to gather data, e.g. .csv files, excel-lists and so on. Ususally they have the advantage, that they require less work in implementing them in your data.</li></ul><p>Let’s go through the different methods I used for this project.</p><p><strong>Web Scraping (Part I):</strong></p><p>The first method we used to gather data was Web Scraping in order to gather data about cities (name, population). Therefore we looked at the <a href="https://en.wikipedia.org/wiki/Main_Page">wikipedia-website</a> which contains a list of all cities by different categories. I selected a list of cities on wikipedia I wanted to use and took a long look at the html-code of the <a href="https://en.wikipedia.org/wiki/List_of_cities_in_the_European_Union_by_population_within_city_limits">website</a>. If you press F12 you can inspect a website’s html-code to see what part of the code is responsible for the website’s appearance:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pitugty7uvnr1oZ2baemwQ.png" /><figcaption>Left: What you see — Right: The website’s html-code</figcaption></figure><p>Now, that I found the data I wanted to use. I had to extract the information contained in the table. Be warned: Web Scraping is a tedious work, which can frustrate you quite a lot — especially if you do this for the first time on the wikipedia-website.</p><p>This is why I didn’t extract the data from this list, but from other wikipedia-websites (the ones who are about a city itself).</p><p>In order to be able to webscrape at all, I needed the correct tools:</p><ul><li><strong>Requests:</strong> To establish a connection and to extract the html-code from a website</li><li><strong>BeautifulSoup:</strong> To extract the data from the html-code</li><li><strong>Pandas:</strong> To create a table from the data in order to be able to work with the data more easily</li></ul><p>I collected the information and stored it in a pandas-dataframe:</p><pre>import requests</pre><pre>from bs4 import BeautifulSoup as bs</pre><pre>import pandas as pd</pre><pre>import unicodedata</pre><pre># cities = [&#39;Berlin&#39;, &#39;Hamburg&#39;, &#39;Frankfurt&#39;,&#39;Munich&#39;,&#39;Stuttgart&#39;,&#39;Leipzig&#39;,&#39;Cologne&#39;,&#39;Dresden&#39;,&#39;Hannover&#39;,&#39;Paris&#39;, &#39;Barcelona&#39;,&#39;Lisbon&#39;,&#39;Madrid&#39;]</pre><pre>cities = [&#39;Berlin&#39;,&#39;Paris&#39;,&#39;Amsterdam&#39;,&#39;Barcelona&#39;,&#39;Rome&#39;,&#39;Lisbon&#39;,&#39;Prague&#39;,&#39;Vienna&#39;,&#39;Madrid&#39;]</pre><pre>def City_info(soup):</pre><pre>ret_dict = {}</pre><pre>ret_dict[&#39;city&#39;] = soup.h1.get_text()</pre><pre>if soup.select_one(&#39;.mergedrow:-soup-contains(&quot;Mayor&quot;)&gt;.infobox-label&#39;) != None:</pre><pre>i = soup.select_one(&#39;.mergedrow:-soup-contains(&quot;Mayor&quot;)&gt;.infobox-label&#39;)</pre><pre>mayor_name_html = i.find_next_sibling()</pre><pre>mayor_name = unicodedata.normalize(&#39;NFKD&#39;,mayor_name_html.get_text())</pre><pre>ret_dict[&#39;mayor&#39;]  = mayor_name</pre><pre>if soup.select_one(&#39;.mergedrow:-soup-contains(&quot;City&quot;)&gt;.infobox-label&#39;) != None:</pre><pre>j =  soup.select_one(&#39;.mergedrow:-soup-contains(&quot;City&quot;)&gt;.infobox-label&#39;)</pre><pre>area = j.find_next_sibling(&#39;td&#39;).get_text()</pre><pre>ret_dict[&#39;city_size&#39;] = unicodedata.normalize(&#39;NFKD&#39;,area)</pre><pre>if soup.select_one(&#39;.mergedtoprow:-soup-contains(&quot;Elevation&quot;)&gt;.infobox-data&#39;) != None:</pre><pre>k = soup.select_one(&#39;.mergedtoprow:-soup-contains(&quot;Elevation&quot;)&gt;.infobox-data&#39;)</pre><pre>elevation_html = k.get_text()</pre><pre>ret_dict[&#39;elevation&#39;] = unicodedata.normalize(&#39;NFKD&#39;,elevation_html)</pre><pre>if soup.select_one(&#39;.mergedtoprow:-soup-contains(&quot;Population&quot;)&#39;) != None:</pre><pre>l = soup.select_one(&#39;.mergedtoprow:-soup-contains(&quot;Population&quot;)&#39;)</pre><pre>c_pop = l.findNext(&#39;td&#39;).get_text()</pre><pre>ret_dict[&#39;city_population&#39;] = c_pop</pre><pre>if soup.select_one(&#39;.infobox-label&gt;[title^=Urban]&#39;) != None:</pre><pre>m = soup.select_one(&#39;.infobox-label&gt;[title^=Urban]&#39;)</pre><pre>u_pop = m.findNext(&#39;td&#39;)</pre><pre>ret_dict[&#39;urban_population&#39;] = u_pop.get_text()</pre><pre>if soup.select_one(&#39;.infobox-label&gt;[title^=Metro]&#39;) != None:</pre><pre>n = soup.select_one(&#39;.infobox-label&gt;[title^=Metro]&#39;)</pre><pre>m_pop = n.findNext(&#39;td&#39;)</pre><pre>ret_dict[&#39;metro_population&#39;] = m_pop.get_text()</pre><pre>if soup.select_one(&#39;.latitude&#39;) != None:</pre><pre>o = soup.select_one(&#39;.latitude&#39;)</pre><pre>ret_dict[&#39;lat&#39;] = o.get_text()</pre><pre>if soup.select_one(&#39;.longitude&#39;) != None:</pre><pre>p = soup.select_one(&#39;.longitude&#39;)</pre><pre>ret_dict[&#39;long&#39;] = p.get_text()</pre><pre>return ret_dict</pre><pre>list_of_city_info = []</pre><pre>for city in cities:</pre><pre>url = &#39;https://en.wikipedia.org/wiki/{}&#39;.format(city)</pre><pre>web = requests.get(url,&#39;html.parser&#39;)</pre><pre>soup = bs(web.content)</pre><pre>list_of_city_info.append(City_info(soup))</pre><pre>df_cities = pd.DataFrame(list_of_city_info)</pre><pre># df_cities = df_cities.set_index(&#39;city&#39;)</pre><pre>df_cities</pre><p>So, first data-set done only two more to go, right? No!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/1*s0FUlO4_jQX3KSfjCxLpFw.gif" /></figure><p>In my eyes, the data-quality was too bad:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yBXgkU0C0z_6xNV82Cu6WA.png" /><figcaption>Data-output from webscraping</figcaption></figure><p>Therefore I decided to ditch this dataset alltogether and look for data with better quality. Google was my friend and I found a file from statista, which contained a clean dataset for all German cities. So I used a .csv-file instead.</p><p>What can we learn from this? Web Scraping is a great tool to gather data which is not gaterable though other means. If you can get it in another way, you’ll make your life a lot easier.</p><p>So, one dataset finally done.</p><p><strong>Data gathering through APIs:</strong></p><p>The easier was to gather data is through APIs. APIs lets you interact with websites in order to get interesting data from them. In our case we wanted to get wheather-data from <a href="https://openweathermap.org/">openweathermap.org</a> and airport-data which we gained through RapidAPI.</p><p>First lets start with the flights.</p><p><strong>Gathering Flight-Data:</strong></p><p>For APIs you usually need a key. In our case we were able to find a key on RapidAPI. Then we extracted the information. Therefore you have to send a request with the correct syntax in order to get the information you want to know:</p><pre>from datetime import datetime, timedelta</pre><pre>airport_icoa = &quot;EDDB&quot;</pre><pre>to_local_time = datetime.now().strftime(&#39;%Y-%m-%dT%H:00&#39;)</pre><pre>from_local_time = (datetime.now() + timedelta(hours=9)).strftime(&#39;%Y-%m-%dT%H:00&#39;)</pre><pre>url = f&quot;https://aerodatabox.p.rapidapi.com/flights/airports/icao/{airport_icoa}/{to_local_time}/{from_local_time}&quot;</pre><pre>import requests</pre><pre>querystring = {&quot;withLeg&quot;:&quot;true&quot;,&quot;withCancelled&quot;:&quot;true&quot;,&quot;withCodeshared&quot;:&quot;true&quot;,&quot;withCargo&quot;:&quot;true&quot;,&quot;withPrivate&quot;:&quot;false&quot;,&quot;withLocation&quot;:&quot;false&quot;}</pre><pre>headers = {</pre><pre>&#39;x-rapidapi-host&#39;: &quot;aerodatabox.p.rapidapi.com&quot;,</pre><pre>&#39;x-rapidapi-key&#39;: flight_api_key</pre><pre>}</pre><pre>response = requests.request(&quot;GET&quot;, url, headers=headers, params=querystring)</pre><pre>from IPython.display import JSON</pre><pre>response.json()</pre><p>The answer you’ll get will be a JSON file, which can be a little bit overwhelming at first glance:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*J3g6TO6DfHUzzp9hLJKIag.png" /><figcaption>JSON-output through APIs</figcaption></figure><p>So we have to convert the data into a readable table:</p><pre>arrivals_berlin = response.json()[&#39;arrivals&#39;]</pre><pre>def get_flight_info(flight_json):</pre><pre># terminal</pre><pre>try: terminal = flight_json[&#39;arrival&#39;][&#39;terminal&#39;]</pre><pre>except: terminal = None</pre><pre># aircraft</pre><pre>try: aircraft = flight_json[&#39;aircraft&#39;][&#39;model&#39;]</pre><pre>except: aircraft = None</pre><pre>return {</pre><pre>&#39;dep_airport&#39;:flight_json[&#39;departure&#39;][&#39;airport&#39;][&#39;name&#39;],</pre><pre>&#39;sched_arr_loc_time&#39;:flight_json[&#39;arrival&#39;][&#39;scheduledTimeLocal&#39;],</pre><pre>&#39;terminal&#39;:terminal,</pre><pre>&#39;status&#39;:flight_json[&#39;status&#39;],</pre><pre>&#39;aircraft&#39;:aircraft,</pre><pre>&#39;icao_code&#39;:airport_icoa</pre><pre>}</pre><pre>import pandas as pd</pre><pre># [get_flight_info(flight) for flight in arrivals_berlin]</pre><pre>arrivals_berlin = pd.DataFrame([get_flight_info(flight) for flight in arrivals_berlin])</pre><pre>arrivals_berlin</pre><p>This will give us this output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/1*B8nE7NZwjmHUSz2pn2HQyA.png" /><figcaption>Pandas DataFrame of JSON output</figcaption></figure><p>This is a format we can work with in the SQL-Database we will create later.</p><p><strong>Gathering Weather Data:</strong></p><p>For this project I used, as before mentioned, Open Weather Map. They provide an API where you can get weather forecasts. All you have to do is to register at their website in order to get a needed API-key.</p><p>Extracting weather-data is almost the same as extracting flight-data. Except we are using a python-library this time to do so: <a href="https://pyowm.readthedocs.io/en/latest/">pyowm</a>. This will make the process a little bit easier.</p><pre>from pyowm import OWM</pre><pre>from pyowm.utils import config</pre><pre>from pyowm.utils import timestamps</pre><pre>import pandas as pd</pre><pre>city = &quot;Berlin&quot;</pre><pre>country = &quot;DE&quot;</pre><pre>owm = OWM(OWM_key)</pre><pre>mgr = owm.weather_manager()</pre><pre># Will it be clear tomorrow at this time in Milan (Italy) ?</pre><pre>forecast = mgr.forecast_at_place(city + &#39;,&#39; + country, &#39;3h&#39;)</pre><pre># answer = forecast.will_be_clear_at(timestamps.tomorrow())</pre><pre>from numpy import nan</pre><pre>def forecast_extraction(forecast_object):</pre><pre>&quot;&quot;&quot;</pre><pre>Given a forecast object from Open weathor Pyhton API,</pre><pre>return a structured dataframe.</pre><pre>:param: forecast object</pre><pre>:returns: a dataframe with specific weather information</pre><pre>&quot;&quot;&quot;</pre><pre>forecast_df = pd.json_normalize({</pre><pre>&#39;time&#39; : forecast_object.reference_time(timeformat=&#39;date&#39;),</pre><pre>&#39;temperature&#39; : forecast_object.temperature(unit=&#39;celsius&#39;),</pre><pre>&#39;precipitation_probabily&#39; : forecast_object.precipitation_probability,</pre><pre>&#39;rain&#39; : forecast_object.rain,</pre><pre>&#39;humidity&#39; : forecast_object.humidity,</pre><pre>&#39;status&#39; : forecast_object.status,</pre><pre>&#39;snow&#39; : [nan if forecast_object.snow is None else forecast_object.snow],</pre><pre>&#39;wind&#39; : forecast_object.wind(&#39;km_hour&#39;)</pre><pre>})</pre><pre>return(forecast_df)</pre><pre>weather_forecast = pd.concat(</pre><pre>[forecast_extraction(weather) for weather in forecast.forecast.weathers]</pre><pre>)</pre><pre>weather_forecast.head()</pre><p>We’ll get an output which will look more or less like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OWNCrEjr7mwnhUatLCv8xg.png" /></figure><h3>Creating a database:</h3><p>We gathered data through Web Scraping, .csv and APIs. Now we have to bring this collected data together in a database. I used MySQL.</p><p>This will be a relativly easy schema, but you should always think about your data first, before you start creating the database itself. What will be the PRIMARY KEY. What can you use as a FOREIGN KEY. How are the different tables related to each other?</p><p>Also another important question to think about first is the data format of the columns in a table. What is a string (CHAR or VARCHAR) or a number (integer, float…)? This question is important, because you might want to do some calculations afterwards and you want to calculate with a number, not with a piece of text. If you are more advanced you might also want to save space in your database. Some formats require more space than others. So if you are using the maximum possible signs in a CHAR, you will waste much space on your harddrive.</p><p>I used this code to create all the tables including PRIMARY KEYs and FOREIGN KEYs:</p><pre>DROP TABLE IF EXISTS cities;<br>CREATE TABLE IF NOT EXISTS cities (<br> key_index INTEGER,<br>    land CHAR(2),<br>    regierungsbezirk INTEGER,<br>    kreis CHAR(2),<br>    verband CHAR(4),<br>    gemeinde CHAR(4),<br>    city VARCHAR(200),<br>    zip_code CHAR(5),<br>    area_in_sq_km DOUBLE,<br>    population_total INTEGER,<br>    population_male INTEGER,<br>    population_female INTEGER,<br>    pop_per_sq_km INTEGER,<br>    state VARCHAR(200),<br>    city_name VARCHAR(200),<br>    city_title VARCHAR(200),<br>    municipality_iso_country varchar(200),<br>    PRIMARY KEY(municipality_iso_country)<br>);</pre><pre>drop table if exists weather; <br>create table if not exists weather (<br> weather_id int auto_increment, <br>    datetime datetime, <br>    temperature float, <br>    wind float, <br>    prob_perc float, <br>    rain_qty float, <br>    snow integer, <br>    municipality_iso_country varchar(200),<br>    primary key(weather_id), <br>    foreign key (municipality_iso_country) references   cities(municipality_iso_country)<br>);<br>-- select * from weather;</pre><pre>drop table if exists airports;<br>create table if not exists airports(<br> name text, <br>    latitude_deg float, <br>    longitude_deg float, <br>    iso_country varchar(10), <br>    iso_region varchar(10),<br>    municipality text, <br>    icao_code varchar(4), <br>    iata_code varchar(6), <br>    municipality_iso_country varchar(200),<br>    primary key(icao_code),<br>    foreign key (municipality_iso_country) references cities(municipality_iso_country)<br>);<br>-- select * from airports;</pre><pre>drop table if exists arrivals; <br>create table if not exists arrivals(<br> arrivals_id int auto_increment, <br>    dep_airport text, <br>    sched_arr_loc_time datetime, <br>    terminal text, <br>    status text, <br> aircraft text, <br>    icao_code varchar(4),<br>    primary key (arrivals_id), <br>    foreign key (icao_code) references airports(icao_code)<br>);</pre><p>The output of this code will be a schema which should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*Y1qrYHZ7edL_lhMiYpPQtw.png" /><figcaption>SQL-Digramm: You can create one by pressing CTRL + R</figcaption></figure><p>You can see the relations between the tables — this is also why such a database is called relational database.</p><p>So everything is prepared for the data I wanted to upload to the database.</p><p>The first data-set i wanted to upload was the .csv-file I had for the cities of Germany. This was very easy. I used the import-feature of MySQL-Workbench. Ok, very easy is a bit too positive. The original file was an excel-file, which I converted into a .csv-file. I worked with excel for a long time, so I converted the data-types of all columns accordingly. Don’t ever do that. I spent hours to understand why I wasn’t able to integrate the data into MySQL. The solution was <em>not </em>to format any data. The database is already set. So this was an unnecessary step, which caused a lot of trouble. Don’t do that and everything will be fine.</p><p>Next, the weather and flight data had to be uploaded to the database. I had this data already. So the easiest way was to upload it via SQLAlchemy.</p><p>First you have to set up some variables:</p><pre>schema=&quot;gans&quot;<br>host= host<br>user= root<br>password= password<br>port=3306<br>con = f&#39;mysql+pymysql://{user}:{password}@{host}:{port}/{schema}&#39;</pre><p>To upload the data:</p><p>Flights:</p><p>airports_cities.dropna().to_sql(&#39;airport_cities&#39;), if_exists=&#39;append&#39;, con=con, index=False</p><p>Weather:</p><pre>weather_data.assign(datetime = lambda x: pd.to_datetime(x[&#39;datetime&#39;])).to_sql(&#39;weather&#39;, if_exists=&#39;append&#39;, con=con, index=False)</pre><p>Done! Done? No, now let’s upload everything to the cloud!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*q0rLtqDyGOxjbIBFbBYYxQ.gif" /></figure><h3>Cloudy with a chance of Lambda</h3><p>For this project I used <a href="https://aws.amazon.com/de/">Amazon Web Service</a>. Here I created a database again and set up a Lambda-function to gather data automatically.</p><p>AWS is a huge platform which offers a vast amount of services. Basically a cloud service provides storage and computing power — and also high security. The benefit of a cloud service is, that you don’t have to bother with such things like the size of your server. If you need more power, you just buy it and drop it again when you don’t need it anymore.</p><p>The first step on the Amazon platform is to create the database. This is done via RDS (Relational Database Service).</p><p>After that you can connect to your newly created database via MySQL-Workbench. The difference is, that you are not working on your own PC anymore. Therefore you have to use an <em>endpoint </em>as address for your server. You should also remember which username you chose when you created your database. MySQL uses <em>root </em>by default, whereas amazon will use <em>admin</em>.</p><p>Now I was able to connect to my database and create the tables the same way as I did on my PC before.</p><p>So far so good, but at the moment we are just using a database which is in the cloud and not on our PC anymore. This is nice, but we are not using the real advantage of the cloud, yet: Automation.</p><p>To achive this last goal we have to use a service which is called Lambda. This is an event-driven service, which runs code (in different programming-languages — not only Python, but I were using it).</p><p>First I had to create a role in order to determine which rights the Lambda-function would have. I’m a beginner, so I chose a role with many rights. The next step was to connect the lambda-funtion to our database. It is important to know that Lambda by itself doesn’t contain all the Python-libraries, I’m used to work with. In order to solve this problem I had to import <em>Layers. Layers </em>are archives which contain the code of the modules.</p><p>So I set up the code in the Lamda-function to download the weather data directly into the database without my own PC as a handler.</p><p>One last step is still missing in order to get the automation running: Creating a trigger, which will run the lambda-function.</p><p>To solve this last problem we will use AWS Cloudwatch. Please read the <a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/RunLambdaSchedule.html">documentation</a> if you want to know more.</p><p>So all steps are done. And everybody is happy, now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/373/1*z9kDtbbj6b7hCuGM9lA7PQ.gif" /></figure><h3>Bonus: Web Scraping (Part II): Why?!</h3><p>As I mentioned before, I was not very happy with the scope of the project. I think a project, even a fictive one has to be logical. For me Airports and E-Scooters were not logical. More than 20 km distance? What is the battery-power of such a thing?! Where do you put your luggage? Does “Gans” want to rent their scooters with a trailer attached? Do you need a special driver’s-license to run such a thing? I had questions…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BwXQygeMVHkWEKnZCEm0hw.jpeg" /></figure><p><a href="https://www.gettyimages.de/detail/foto/motor-scooters-pulling-trailer-with-pigs-lizenzfreies-bild/93522390">https://www.gettyimages.de/detail/foto/motor-scooters-pulling-trailer-with-pigs-lizenzfreies-bild/93522390</a></p><p>So I decided to think about a viable alternative to airports. When did I use e-scooters before? Small distances within the city. So the solution would be to go to a place within the city. Why you’d want to go there? Maybe because there might be an event or something.</p><p>This was what I was thinking when I decided to change the scope of the project, ditched the airport and all my questions related to such a dubious business-model and looked for websites where I could gather data for events — preferably in the future. I found two: eventim.de and meinestadt.de. Usually they are not used to gather information about events within a whole country. Usually you buy ticket on their website. I thought if you can buy, you can also gather information.</p><p>I was right (and also so wrong), but to be honest I enjoyed this journey quite a lot.</p><p>First of all, all libraries, which I used before didn’t work on these websites. They were blocking my get-requests right away. A get-request to eventim.de even let my python-kernel crash several times.</p><p>This was when I contacted Joan, our supervisor, who helped me to choose the right library for this task: <a href="https://selenium-python.readthedocs.io/">Selenium</a>. Selenium is an amazing library, which is simulating human interactions with a website and so circumventing the detection as a bot (or webscraper). It is not as easy as BeautifulSoup and you need to do some preparation beforehand.</p><p>Selenium uses your webbrowser to gather the data (you can choose which one you want to use) I chose Chrome. So I downloaded the Chrome-Driver, set up Selenium to use it and was finally able to connect to both websites. I chose meinestadt.de, because they had the better search-function for my purposes.</p><p>Everything seemed fine, until I ran into the <strong>GDPR</strong> (<strong>G</strong>eneral <strong>D</strong>ata <strong>P</strong>rotection <strong>R</strong>egulation), which took all the fun away I had for several hours. After using google without finding a working solution I turned to another instructor, Hana, who is almost a professional Web Scraper. She said, no, I say she is. So the mean of it is almost professional.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*Lflz4OuTV10mXQlmWLqp8w.gif" /></figure><p>She gave me the correct code and I was able to go on Web Scraping.</p><pre>from selenium import webdriver</pre><pre>from selenium.webdriver.common.keys import Keys</pre><pre>from selenium.webdriver.common.by import By</pre><pre>from selenium.webdriver.support.ui import WebDriverWait</pre><pre>from selenium.webdriver.support import expected_conditions as EC</pre><pre>import time</pre><pre>PATH = &quot;C:\Files_for_Python\chromedriver.exe&quot;</pre><pre>driver = webdriver.Chrome(PATH)</pre><pre>driver.get(&quot;https://veranstaltungen.meinestadt.de/augsburg/alle/alle?words=&quot;)</pre><pre><br>#Thank you Hana</pre><pre>WebDriverWait(driver,10).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,&quot;iframe[id^=&#39;sp_message_iframe_620940&#39;]&quot;)))</pre><pre>WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, &quot;button[class^=&#39;message-component message-button no-children focusable button-responsive-primary sp_choice_type_11&#39;]&quot;))).click()</pre><pre>print(driver.title)</pre><pre>search = driver.find_element(By.ID, &quot;ms_resultlist_7165239&quot;)</pre><pre>event_name = search.find_elements(By.CLASS_NAME, &quot;ms-result-item-highlite&quot;)</pre><pre>link_all = search.find_elements(By.TAG_NAME, &quot;a&quot;)</pre><p>This gave me the raw code. I just used the part I was interested in and saved it in the variable <em>search</em>. I was able to determine the part of the html-code where all event-names were stored and saved it in the variable <em>event_name</em> (creativity!). The links I was interested in, I searched by the tag-name and stored them in <em>link_all</em>.</p><p>Now all I had to do was to extract the text and append it to a list:</p><pre>event_list = []</pre><pre>len(event_name)</pre><pre>for event in event_name:</pre><pre>event_list.append(event.text)</pre><pre>print(event_list)</pre><p>This gave me this list of event-names:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*kpE77jUSpfc059lSC40uXw.png" /></figure><p>I went through my data and realised, that I already had most I wanted:</p><pre>for link in link_all:</pre><pre>print(link.text)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/1*mOonAXJvyjq8V20FWJ6OvA.png" /></figure><p>So I had just to take the right data and put it into the right list:</p><p>The kind of event:</p><pre>counter = 0</pre><pre>event_class_list = []</pre><pre>for i in range(15):</pre><pre>event_class_list.append(link_all[counter].text)</pre><pre>counter+=4</pre><p>The location where an event was happening:</p><pre>counter = 2</pre><pre>event_location_list = []</pre><pre>for i in range(15):</pre><pre>event_location_list.append(link_all[counter].text)</pre><pre>counter+=4</pre><p>Now there was just one dataset missing. When was an event happening? So I needed the dates and the time an event would start.</p><pre>event_dates_times = search.find_elements(By.TAG_NAME, &quot;time&quot;)</pre><p>I created again two lists and stored the data:</p><pre>counter = 0<br>time_list = []<br>date_list = []<br>for edt in event_dates_times:<br>    if (counter % 2) == 0:<br>        date_list.append(edt.text)<br>    else:<br>        time_list.append(edt.text)<br>    counter += 1</pre><h3>Conclusion:</h3><p>I really liked this project. I found a way to gather data, store it and collect data over a long time.</p><p>I also found out, that Web Scraping can be very frustrating, but the reward is also great.</p><p>Thanks a lot to Joan and Hana for helping me with my out-of-scope task!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=417e9a55e70d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>