/html/body/div/main/div/div/div[2]/div/div/div/div[1]/div/div***[4]***/div/div[2]
The div[4]
element keeps changing. If a new item comes into the web, the div number changes.
How do I handle this?
/html/body/div/main/div/div/div[2]/div/div/div/div[1]/div/div***[4]***/div/div[2]
The div[4]
element keeps changing. If a new item comes into the web, the div number changes.
How do I handle this?
If nothing in the web page is predictable, then you're hosed: you can't find gold in a sea of shifting data unless you have something to hold on to.
If there's some constant factor in the web page that is stable, whether it's the structure, an ID value, or some textual content, then tell us what it is, and we can help you translate that description into XPath.
We should always prefer the relative path to avoid these situations, don't use absolute XPath
Don't use absolute xpath at all. Use relative xpath.
It is recommended to use CSS over XPath as it is faster
Web elements could be located using tag, attributes, parent, child, text and lot more. Just see what is the easiest approach and clearest approach.
For instance, the xpath you mentioned doesn't give any idea about the element. The locator we use should be mostly self-descriptive.
One should be able to tell what element the locator is pointing to without the need of rechecking the DOM.
Eg: //button[@id="login"], one can easily say that it's a login button by just seeing the locator.
In your particular case as far as I understood your target element is getting shifted in the list after a new item is added before it. If this is the case you can get the access to that element from the end of the list.
For example this element could be always the last one. Then you should use:
/html/body/div/main/div/div/div[2]/div/div/div/div[1]/div/div[last()]/div/div[2]
or if it is always pre-last then
/html/body/div/main/div/div/div[2]/div/div/div/div[1]/div/div[last()-1]/div/div[2]
//div
is absolute or relative? In xpath you just push off the previously located node(s) when look up the next one. And this does not really matter if the previous one is the root or not. It is all relative.
Always write short relative path
which is independent of DOM hirarachy changes as much as possible.
In your particular case how about focusing on just last div unique properties for identification.
Ex: 'div[AnyUniqueProperty="Value"]
Some things to try when handling this:
/html/body/div/main/div/div/div[2]/div/div/div/div[1]/div/
/div/div[2]
One note: You should consider not only brittle, accessibility and performance is important. Performance will vary depending on the method you use. For example ID is faster than XPath.
This will be important as your tests increase.
//*[@id='...']
under the hood.