5 Mar 2025 · 4 min read · EN

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

To conclude this example, in this second part, we will look at the auxiliary code used and the main loop that retrieves the coordinates.

Auxiliary code

We define two functions: One that is responsible for finding at least two streets within the possible list of 4 obtained from the Excel maps, and another that is responsible for finding the GPS latitude and longitude within the text extracted from the URL returned by the Google Maps server. Here is the code.

def obtener_campos(fila):
    print(fila)
    if not fila[1] or not fila[2]:
        return fila[4], fila[5], fila[3]
    else:
        return fila[1:4]


def extraer_coordenadas(string):
    # Pattern for an @ followed by 2 float numbres separates by comma
    patron = r'@(-?\d+\.?\d*),(-?\d+\.?\d*)'

    coincidencia = re.search(patron, string)

    if coincidencia:
        # get strings and convert to float
        latitud = float(coincidencia.group(1))
        longitud = float(coincidencia.group(2))

        # Check validity
        if -90 <= latitud <= 90 and -180 <= longitud <= 180:
            return (latitud, longitud)
        else:
            print("Advertencia: Coordenadas fuera de rango.")
            return None
    else:
        # Return None if not found
        return None

The first function is very simple and only determines the first two non-empty values it finds in the list passed as a parameter. The second function uses the capabilities of the RE library to handle regular expressions by applying a pattern that looks for an ‘@’ sign followed by two floating-point numbers separated by a comma. It converts the extracted text into floats and then verifies that they fall within the valid range for latitude and longitude values. If the pattern is not found, it returns None (meaning the street intersection could not be located).

Web driver operation

The following block of code is the one that actually handles the automation using the web driver.

# El acceso al navegador
def obtener_coordenadas(resultado, driver):
    # lleno el input de busqueda con el texto
    WebDriverWait(driver,60).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input#searchboxinput"))).send_keys(resultado)
    # cliqueo en el icono de la lupita
    WebDriverWait(driver,60).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "span.google-symbols"))).click()
    # espero un ratito
    time.sleep(5)
    # leo el actual url
    url = driver.current_url
    # borro el contenido del input
    WebDriverWait(driver,60).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input#searchboxinput"))).clear()

    return extraer_coordenadas(url)

There is where the < input> element in the DOM of the web page is located, which is where the search parameters are entered (the text formed with the streets and the neighborhood or area). All of this is accomplished in a single line of code using method chaining. Then, using similar logic, the magnifying glass icon is located, and the click() command is sent to it. We wait a reasonable amount of time (5 seconds). We read the current URL from the driver. Next, we clear the entered text (which may have been altered by the server) so it can be used in the next cycle. Finally, we extract the coordinates using the auxiliary function and return them.

The main loop

Alright, now is where we need to put everything together and make it work. This piece of code is responsible for opening a .csv file for reading, which contains the information from the Excel sheet, and it opens a copy of the same file for writing, adding two columns with the latitude and longitude extracted using the web driver.

with open('data_excel.csv', 'r') as archivo_in, open("data_coordinates.csv", 'w', newline='') as archivo_out:
    # Creation of csv objects for both files
    lector_csv = csv.reader(archivo_in, delimiter=';')
    escritor_csv = csv.writer(archivo_out, delimiter=';')

    # Load first line (head) and append two new columns
    encabezados = next(lector_csv, None)
    # New columns
    encabezados.append('latitud')
    encabezados.append('longitud')
    # Save new head to output file
    escritor_csv.writerow(encabezados)

    # Loops over every line of input file
    for fila in lector_csv:
        # using functions capture streets and neighborhood
        campos = obtener_campos(fila)
        # print(campos) // debug
        # format string for maps search (calle1/3 & calle2/4, localidad)
        resultado = f"{campos[0]} & {campos[1]} , {campos[2]}"
        print(resultado) # Debug also
        latitud, longitud = obtener_coordenadas(resultado, driver)
        # Agrego la latitud y la longitud
        fila.append(latitud)
        fila.append(longitud)
        # Escribo la fila en el archivo
        escritor_csv.writerow(fila)

We start by creating two CSV objects that represent the input and output tables. From the input table, we obtain the headers, add two new columns for latitude and longitude, and then incorporate this extended header into the output file. Next, we go through each line of the input file, capturing the fields with the street names and locality using the auxiliary function. We then construct a string in the necessary format for Google Maps to accept it. At this point, we pass this information to the web driver, which, through the corresponding function, returns the geographic data. We add this data to the new row and finally incorporate it as a new line in the output file. Thanks to the use of with , when the loop finishes, all files will be closed correctly.

Conclusions

As I have already mentioned, this article is not intended as a formal guide to using automation in Python, but rather as a demonstration of how much can be accomplished with just a little code. It served to solve a specific problem and advance a much more complex study than what is shown here in a very summarized way. I hope it serves as an example for others to approach solving similar tasks.