google-mapsselenium-webdriverweb-scrapingweb-crawlerhtmlelements

How can I locate elements in Selenium to search for Google Place IDs in the search box?


I'm trying to locate the searchbox in Google Place IDs website, and I tried By.ID, By.CLASS_NAME, By.XPATH but I failed.

place_id_url = "https://developers.google.com/maps/documentation/javascript/examples/places-placeid-finder#maps_places_placeid_finder-typescript"

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

driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()),
                         options = options)

driver.get(place_id_url)

#target the search input field
searchbox = WebDriverWait(driver, 5).until(EC.element_to_be_clickable((By.XPATH, "//input[@placeholder='Enter a location']")))
searchbox.clear()

keyword = "Dunham Park"
searchbox.send_keys(keyword)

Here is the element information

<input id="pac-input" class="controls pac-target-input" type="text" placeholder="Enter a location" autocomplete="off" style="position: absolute; left: 188px; top: 0px;">

"//html/body/div[2]/div/div/div[4]/input"

I also tried this code but failed too.

place_id_url = "https://developers.google.com/maps/documentation/javascript/examples/places-placeid-finder#maps_places_placeid_finder-typescript"

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

driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()),
                         options = options)

driver.get(place_id_url)

driver.find_element(By.XPATH,"//html/body/div[2]/div/div/div[4]/input").send_keys("Dunham Park" + "\n")
#driver.find_element(By.CLASS_NAME, "controls pac-target-input").send_keys("Dunham Park" + "\n")
#driver.find_element(By.ID, "pac-input").send_keys("Dunham Park" + "\n")

I'm not sure if Google blocks to locate elements to prevent crawling or something. If not, please let me know. Thanks.


Solution

  • The main problem was that the element you are looking for is in an IFRAME. You need to switch context into the IFRAME before locating the element and then type.

    NOTE: As of Selenium 4.6+, you no longer need to manage your own drivers. DriverManager will do that for you.

    I fixed a few other issues and simplified some things as well. This is tested code.

    driver = webdriver.Chrome()
    driver.maximize_window()
    
    url = "https://developers.google.com/maps/documentation/javascript/examples/places-placeid-finder#maps_places_placeid_finder-typescript"
    driver.get(url)
    
    keyword = "Dunham Park"
    wait = WebDriverWait(driver, 10)
    wait.until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR, "iframe[src*='geo-devrel-javascript-samples.web.app']")))
    wait.until(EC.visibility_of_element_located((By.ID, "pac-input"))).send_keys(keyword)
    
    driver.quit()