5 Mar 2025 · 6 min read · EN

A practical example of web scrapping/automation using Selenium in python (Part 1/2)

An alien browsing the web

The problem

Some months ago I was involved in a colaboration between University and a survey consulting firm. The firm found that in the last decades, people tend to lie to political pre electoral surveys. That make very difficult to show clear insights to the clients who ordered the survey. Drawing on the idea that there are ‘witness polling stations’ which, over many elections, tend to align with the overall election result, it was decided to find a similar effect: methods or places where the results of polls aligned (within a margin of error) with the electoral results. It was decided to discard online surveys since they were the ones that diverged the most from the overall result. It was also found that automated surveys (via landline calls) could not be considered relevant because they did not represent the entire age range of the population. Therefore, it was determined that the best source of data would be in-person surveys, where there is a better understanding of the social conditions of the respondent. However, we faced the problem we tried to solve using browser automation: the information on electoral districts is described in geographic data files, but the in-person surveys conducted do not have (at first glance) any information that allows us to link the respondent to the district they belong to and for which we know the electoral result. Additionally, the survey data was stored in SPSS-type databases, which are not directly readable by Python (although there are ongoing projects to address this).

Things start to align

But fortunately, some information could be exported to Excel files, albeit with a dramatic twist: What was generated was an Excel file in which, for each pollster and day, a new sheet was added to the document. In each sheet, a map of the block (or neighborhood, block, etc.) where the pollster was supposed to work was DRAWN. In each sheet, we could find (in different cells) the survey result index, the neighborhood/city/zone, the date of the survey, and up to four street names surrounding the block(s) of the survey. Extracting that information from the Excel file was a task that deserves its own article. But ultimately, after reviewing those Excel files, a .csv file was extracted containing the survey index, the date, the neighborhood, city, or region, and up to four street names.

Finding the coordinates

As we can all notice, Google Maps can find a location if we provide it with the names of two intersecting streets and the area where this occurs (since different neighborhoods can have the same street names intersecting). And if we look closely, Google Maps places the GPS coordinates of the cursor displayed on the screen in the address bar (which, in turn, represents the intersection of the streets). Therefore, we can obtain the information we need by typing the street names and the area into the search box, clicking the magnifying glass, and then reading the browser’s address bar. The only issue is that we would have to do this hundreds or thousands of times, depending on the number of survey records we have. Thus, we should find a way to automate this process. And we have to perform this task using a web driver because the API search options not only do not support this type of search but also involve a monetary cost.

Hands dirty

As a data scientist, I usually solve problems with the simplest and most straightforward code possible. Therefore, you won’t find the best examples of OOP or Clean Code here, and I am very sure that other developers will easily find more efficient and elegant ways to solve these problems. With that disclaimer out of the way, let’s look at the Python code I used, and we’ll try to explain step by step what it does. Let’s start by explaining that when we want to programmatically interact with a web browser (in this case, Google Chromium on Linux), we need to use a software resource that acts as an intermediary between our code and the complex piece of software that is a browser. This resource is called a web driver, and it provides us with objects (with attributes and actions) for each HTML element displayed by the browser. This resource must be installed on the system, and that depends on each browser version and operating system. We won’t cover that task here. With the web driver, we can locate the anchor () where the Google Maps search magnifying glass is and ‘virtually click’ it to initiate the search task on Google’s server. This can be done either invisibly or visibly, meaning we can choose whether or not to see what the browser is doing. Specifically we will use the Selenium web-driver. In the following code, we will load all the necessary libraries to activate the web driver, access the elements of the displayed page, and make it work visibly. And some other standard DS utilities.

# Libraries

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
# DS
import csv
import re

First, we load the web driver. Then, the module that allows us to pause actions while waiting for the server to respond (WebDriverWait). Next, the module that informs us if a particular element is already loaded in the browser (EC). By is the class that provides standard methods for locating elements in the DOM of the web page (ID, name, class, XPath, etc.). Options allows us to add parameters to the web driver’s operation. Service and ChromeDriverManager enable specific management of Chrome/Chromium. csv is used to read and write the program’s input and output files. And re is used to analyze and extract the coordinates from the address bar.

Configuring web-driver

I the following code we proced to parametrize our web-drive for this specific task.

options = Options()
options.add_argument('--disable-dev-shm-usage')
options.add_argument('--start-maximized')
options.add_argument('--disable-extensions')
options.add_argument('--disable-infobars')
options.add_experimental_option('detach', True)
#
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options)

# master url
driver.get("https://maps.google.com")

We create the options object and add arguments to it using the .add_argument method. First, we disable the use of shared memory in Linux environments to reduce memory usage. Then, we start it maximized (since the intention is to show how the automation works). Third, we set the argument to disable any extensions that the browser might have installed, thus gaining speed and reducing memory and CPU usage. Fourth, we disable the resource information bars of the web driver. And finally, we make each operation ‘forget’ the previous one, which facilitates debugging by avoiding huge stacks. Once the options object is configured, we incorporate it into the web driver and create it. And lastly, we make the page that the web driver loads be the Google Maps page.

In the second part of this article, we conclude with auxiliary code and the main loop