Handle elements that have changing ids all the tim

2020-02-13 05:03发布

I am running the script to automate test cases and having this unique problem. I have detected and used IDs of the elements for click etc. purpose. However, all of a sudden these ids have changed and the script works no more. Another weird thing is those IDs are same as in script when inspected in Chrome but different in Firefox driver browser.

Firebug for test driver: -

<p class="description" onclick="selectElementTextListForIE(this,'tile29', 'tile19');selectElementTextList(this,'tile29', '')" id="tile29_span_0_0">
                                                            Platinum
                                                        </p>

Chrome inspector for same element: -

<p class="description" onclick="selectElementTextListForIE(this,'tile20', 'tile19');selectElementTextList(this,'tile20', '')" id="tile20_span_0_0">
                                                            Platinum
                                                        </p>

Also, what could be the best strategy for detecting such elements whose IDs are generated on run. I even tried using XPATH but that too contains id's reference eg. @id="tile276_input

Any help will be appreciated.

Thanks.

Abhishek

3条回答
Bombasti
2楼-- · 2020-02-13 05:20
WebElement element = driver.getElement(By.cssSelector("[id^='title']);

Or

WebElement element = driver.getElement(By.cssSelector("id:contains('title')"));

You Can use this element to do desired actions.

查看更多
乱世女痞
3楼-- · 2020-02-13 05:41

You also can try contains and starts-with() for such things

driver.findElement(By.xpath("//*[contains(@id,'title')]"))

or

driver.findElement(By.xpath("//* [start-with(@id,'title')]"))
查看更多
来,给爷笑一个
4楼-- · 2020-02-13 05:47

You can utilize CSS for this. For your element, looks like its:

<* id="tile276_input" />

What you need to do is find out what is changing about it. I assume it's the number inbetween. If it is, then your selector would look something like:

By.cssSelector("*[id^='tile'][id$='input']")

This will look for anything that has an ID that "starts with tile" and "ends with input. In our case, "tile276_input" matches that.

See this article if you want more information

查看更多
登录 后发表回答