Peyton Fry
Peyton Fry

Reputation: 21

How to find element with dynamic id through Selenium Webdriver

I am new to using webdriver in Python with Selenium and have run into a barrier on something I am working on to automate some data extraction from a webportal. I am trying to enter a date into a textbox, but I my script returns a NoSuchElementException no matter which way I try to search for the element.

Using Chrome, I can use the below ID to easily identify the element in the inspect window, but finding it with Python has been impossible.

HTML element I am trying to isolate:

input id="6A8A7718100001256A44465A5ED3AEAC-toDate" type="text" value="01/15/2019" size="10" maxlength="10" onchange="validateDateField('to', '6A8A7718100001256A44465A5ED3AEAC-fromDate', '6A8A7718100001256A44465A5ED3AEAC-toDate', '6A8A7718100001256A44465A5ED3AEAC-absRangeErr')"

Here is what I have tried:

from_date = driver.find_elements_by_id("6A8A7718100001256A44465A5ED3AEAC-fromDate")
from_date = driver.find_element_by_xpath("//input[@id='6A8A7718100001256A44465A5ED3AEAC-fromDate']")
from_date = from_date = driver.find_element_by_css_selector("input[id='6A8A7718100001256A44465A5ED3AEAC-fromDate']")

Any help is appreciated, thanks!

Upvotes: 1

Views: 7048

Answers (2)

undetected Selenium
undetected Selenium

Reputation: 193108

To send a date i.e. a character sequence into the textbox as the desired element is a dynamic element you have to induce WebDriverWait for the element to be clickable and you can use either of the following solutions:

  • Using CSS_SELECTOR:

    WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input[id$='-toDate'][onchange*='-toDate']"))).send_keys("01/16/2019")
    
  • Using XPATH:

    WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[contains(@id, '-toDate') and contains(@onchange, '-toDate')]"))).send_keys("01/16/2019")
    
  • Note : You have to add the following imports :

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

You can find a detailed discussion in Selenium “selenium.common.exceptions.NoSuchElementException” when using Chrome

Upvotes: 0

cullzie
cullzie

Reputation: 2755

The alphanumeric characters before the '-toDate' seem to be auto generated. This means that they may change between builds of the site or may be dynamically created when the js runs.

Therefore I would use the contains keyword in xpath as it should be more robust against these changes.

to_date = driver.find_element_by_xpath("//input[contains(@id, '-toDate')]")
from_date = driver.find_element_by_xpath("//input[contains(@id, '-fromDate')]")

Upvotes: 3

Related Questions