Salma Madini
Salma Madini

Reputation: 15

How to handle dynamic changing ID's In XPath?

I'm trying to automate login into a website. The id of email box changes each time I search for the page

For example:

//*[@id="undefined-undefined-E-mail-53172"]

When I refresh the page:

//*[@id="undefined-undefined-E-mail-33458"]

So I have to change the code each time like:

driver.find_element_by_id("undefined-undefined-E-mail-53172").send_keys("[email protected]")

driver.find_element_by_id("undefined-undefined-E-mail-33458").send_keys("[email protected]")

And when I refresh again, it doesn't work.

Upvotes: 0

Views: 7937

Answers (3)

StyleZ
StyleZ

Reputation: 1273

You can do it 2 ways:

1/ check if somekinda element contains something ( like part of a string, which someone has already answered in a different answer ... )

2/ The one that I use -> using a full Xpath. Here is how you do that:

  • Download this ( or something like ) this extension https://chrome.google.com/webstore/detail/xpath-helper/hgimnogjllphhhkhlmebbmlgjoejdpjl

  • Go to the website and copy xpath ... when you get xpath that contains a specific ID ( example: //*[@id="5633040"]/div/input , you will just go above that ID and you will try to create a static XPath ( thats what is this extension good for ) .. //*[@id="app_content"]/div/div/form/div[1]/div/div <- lets say this is above that //*[@id="5633040"]

  • so if you put something like this in your xpath search, you should get the same result as with dynamic one //*[@id="app_content"]/div/div/form/div[1]/div/div/div/div/input or this one if there is more divs //*[@id="app_content"]/div/div/form/div[1]/div/div/div[number]/div/input

P.S -> if you cant install extensions, you will just have to try to see if you typed it right and it works

~ Hope it helps :)

Upvotes: 0

Aditya Teja Gaddam
Aditya Teja Gaddam

Reputation: 27

Can you try this it will work

driver.findElement(By.Xpath("//*[contains(@id,'undefined-undefined-E-mail')]").sendKeys("[email protected]");

or

driver.findElement(By.Xpath("//*[starts-with(@id,'undefined-undefined-E-mail')]").sendKeys("[email protected]");

Upvotes: 1

KunduK
KunduK

Reputation: 33384

To handle dynamic element induce WebDriverWait and element_to_be_clickable() since ID is dynamic use starts-with() xpath expression.

WebDriverWait(driver,20).until(EC.element_to_be_clickable((By.XPATH,"//input[starts-with(@id,'undefined-undefined-E-mail-')]"))).send_keys("[email protected]")

Or

WebDriverWait(driver,20).until(EC.element_to_be_clickable((By.XPATH,"//*[starts-with(@id,'undefined-undefined-E-mail-')]"))).send_keys("[email protected]")

Note: You need following imports to execute above code.

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

Upvotes: 1

Related Questions