Search code examples
pythonselenium-webdrivergoogle-formsinspect-element

How to fix "IndexError" on Selenium when trying to automate filling out google form text box? (I used inspect element to find class name of text-box)


Essentially I am trying to automate/autofill a google form by using selenium and inspect element to find the class name. I am especially having trouble finding the solution to an "IndexError" problem when I try to input text into a "short answer" section of the google form. I am a beginner in Python so sorry if this may come across as a very low-level issue.

from selenium import webdriver

option = webdriver.ChromeOptions()
option.add_argument("-incognito")

browser = webdriver.Chrome(executable_path="path to selenium")

option = webdriver.ChromeOptions()
option.add_argument("-incognito")
email = "my email address to sign into the google form"

browser = webdriver.Chrome(executable_path="path to selenium", options=option)
browser.get('url of google form')

sign_in = browser.find_elements_by_class_name("whsOnd zHQkBf")
sign_in[0].send_keys(email)

Next = browser.find_elements_by_class_name("VfPpkd-RLmnJb")
Next[0].click()

textboxes = browser.find_elements_by_class_name("quantumWizTextinputPaperinputInput exportInput")
textboxes[0].send_keys("name")
    
radio_buttons = browser.find_elements_by_class_name("freebirdFormviewerComponentsQuestionCheckboxRoot")
radio_buttons[1].click()


submit=browser.find_element_by_class_name("appsMaterialWizButtonPaperbuttonLabel quantumWizButtonPaperbuttonLabel exportLabel")
submit.click()

Solution

  • Are you sure sign_in actually has anything stored in it? It looks to me that those class names are auto generated when the page loads in, so it could that there is not actually a web element with the class name "whsOnd zHQkBf". It would be better to use xpath and use a relative path to your short form input field. This way if the general layout of the page changes you can still find your web element, making the solution more robust.

    Updated:

    Following code taken directly from Waits Selenium Python API Documentation and can be used to fix "NoSuchElement" exception or "element not interactable" in particular situations.

    '''

    from selenium import webdriver
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    
    driver = webdriver.Firefox()
    driver.get("http://somedomain/url_that_delays_loading")
    try:
        element = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.ID, "myDynamicElement"))
        )
    finally:
        driver.quit()
    

    '''

    You may use By.xpath or any other plethora of identifiers. If this code times out, then the element you are looking for does not exist.