How to locate/find element whose ID and xpath changes on every refresh - Selenium WebDriver Java
Usually when ID or Class attributes are dynamic, you need to look for them using: other attributes/by their dependence to static tags.
Here is an example of looking for a "Compose" button in Gmail. It has: - Dynamic ID - Dynamic Class - One static unique attribute
Here is the HTML code:
<div class="T-I J-J5-Ji T-I-KE L3" tabindex="0" role="button" style="-moz-user-select: none;" gh="cm">COMPOSE</div>
So my xpath would be:
//div[@gh='cm']
Or imagine that you are looking for a "Send message" button on Gmail. It has: - Dynamic ID - Dynamic Class - One static unique attribute
The HTML code:
<div id=":ly" class="T-I J-J5-Ji aoO T-I-atl L3" tabindex="1" role="button" style="-moz-user-select: none;" data-tooltip="Send (Ctrl-Enter)" aria-label="Send (Ctrl-Enter)" data-tooltip-delay="800">Send</div>
This example uses CSS selector:
[aria-label*='Enter)']
the rule here is, when something is dynamic, look for it by using something static as a reference.
In your case it will be:
//div[@class="form-group event-date"]/input
works if your div-class is not dynamic.
Uziii
Updated on June 04, 2022Comments
-
Uziii about 2 years
I am working on selenium webdriver using java, and I am facing a problem. I have a field on a page whose id and xpath changes every time that page is loaded. Like, when I open that page manually, I can see some id and xpath, but when my test run, the id, xpath has changed. Example,
.//*[@id='dp1445259656810'] .//*[@id='dp1445260051638'] .//*[@id='dp1445260078674'] .//*[@id='dp1445260154173']
these are the xpaths that are created every time I refresh my page. How can I locate/find such an element during my run test. Any help will be highly appreciated.
Below is the HTML code for the field.
<div class="form-group event-date"> <div class="input-group"> <input id="dp1445260154173" class="form-control ng-pristine ng- untouched ng-valid ng-isolate-scope hasDatepicker" enter-action="datePickerEnter(event)" allow-empty="" has-datepicker="" ng-model="eventSeries.newEvent.date" placeholder="Event Date"/> <span class="input-group-addon"> <i class="fa fa-calendar"/> </span> </div> </div>
-
Uziii over 8 yearsThanks, looked into the code, and found one static parameter that did not change on every refresh.
-
Selrac almost 8 yearsIs there a way to find out which elements are static and which dynamic without having to refresh the page?
-
SHAH MD IMRAN HOSSAIN about 6 yearswhat is the right syntax for this, i am getting error. element_home = driver.find_element_by_xpath("//div[@class="octicon octicon-mark-github"])