Search code examples
pythonseleniummechanize

Input fields not accessible using inspect element when using programmatic web browsing


When I use mechanize, selenium libraries to run a url ("www.maps.google.com" in this case),

Chrome opens with a note saying that "Chrome is being controlled by an automated testing software".

But when I try to inspect element, there is only one element: body. All other inputs and buttons are not showing.

I want to automate the process to find distance between two addresses, so how do I solve the above problem?

from selenium import webdriver

driver = webdriver.Chrome(executable_path='C:/chromedriver.exe')
# Go to your page url
driver.get('https://www.google.com/maps')
# Get button you are going to click by its id ( also you could us find_element_by_css_selector to get element by css selector)
button_element = driver.find_element_by_id('searchbox-directions')
button_element.click()
dest_add = driver.find_element_by_class_name("tactile-searchbox-input")
dest_add.send_keys("Agra")
start_add = driver.find_element_by_class_name("tactile-searchbox-input")
start_add.send_keys("Jaipur")

For example this doesn't work. Since, there are no input fields so naturally, no elements with the class name "tactile-searchbox-input".


Solution

  • Induce WebDriverWait() and wait for element_to_be_clickable() and following css selector

    driver.get('https://www.google.com/maps')
    WebDriverWait(driver,20).until(EC.element_to_be_clickable((By.ID,"searchbox-directions"))).click()
    WebDriverWait(driver,20).until(EC.element_to_be_clickable((By.CSS_SELECTOR,"input[aria-label*='starting point']"))).send_keys("Agra")
    WebDriverWait(driver,20).until(EC.element_to_be_clickable((By.CSS_SELECTOR,"input[aria-label*='destination']"))).send_keys("Jaipur")
    

    You need to import below libraries.

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    from selenium.webdriver.common.by import By
    

    To click on search button try this.

    WebDriverWait(driver,20).until(EC.element_to_be_clickable((By.XPATH,"(//button[@aria-label='Search'])[last()]"))).click()