Search code examples
pythonpython-3.xgoogle-chromeselenium-webdriverpycharm

Title of 5 results in Google Maps


I am trying to print the names of 5 first engineering schools from google maps. I have made the following code but I can't find out why there are no results after runing!

Can you help please?

Many thanks in advance.

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import time

chrome_options = Options()
chrome_options.add_experimental_option("detach", True)

driver = webdriver.Chrome(options=chrome_options)

driver.get("https://www.google.com/")
driver.find_element(By.ID, "L2AGLb").click()

driver.get("https://www.google.com/maps")

# Wait for the page to load and display the search box
time.sleep(3)

# Input the search query for "parisserie in Paris" and press Enter
search_box = driver.find_element(By.ID, "searchboxinput")
search_box.send_keys("engineering school in london")
search_box.send_keys(Keys.RETURN)

# Wait for the search results to load
time.sleep(5)

# Get the names of the first 5 results using "aria-label"
results = driver.find_elements(By.XPATH, "//a[@class='place-result-container-place-link']/@aria-label")

# Print the names for debugging
for i, result in enumerate(results[:5], start=1):
    print(f"Result {i}: {result}")

# Close the browser
driver.quit()

I am trying to get some help


Solution

  • Here's a complete script (based on your settings), which goes directly to the URL with the search results, and uses a better selector for finding the school names:

    from selenium import webdriver
    from selenium.webdriver.chrome.options import Options
    import time
    
    chrome_options = Options()
    chrome_options.add_experimental_option("detach", True)
    driver = webdriver.Chrome(options=chrome_options)
    driver.get("https://www.google.com/maps/search/engineering+school+in+london")
    time.sleep(5)
    elements = driver.find_elements('css selector', '[role="main"] a[href*="google"]')
    results = [element.get_attribute("aria-label") for element in elements]
    for i, result in enumerate(results[:5], start=1):
        print(f"Result {i}: {result}")
    driver.quit()