Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
273 views
in Technique[技术] by (71.8m points)

Java Selenium webdriver expression finding dynamic element by ccs that starts with and ends with

I have the below HTML element that I need to find. Now, this "id" name is dynamic in the way that the int "0" at the end will change, but I know what it will be. The first int in "0-0" will also change, but it doesn't matter what it will be.

<div id="ui-select-choices-row-0-0">

I've tried the below code that looks for an element that starts with "#ui-select-choices-row-" and ends with the desired input of "int", but it's not finding it as expected. Any suggestions on what I'm doing wrong here?

Attempt 1:

driver.findElement(By.cssSelector("div[id^='#ui-select-choices-row-'] and div[id$='"+int+" div']"));

Attempt 2:

driver.findElement(By.cssSelector("div[id^='ui-select-choices-row-'] and div[id$='"+int+"']"));
question from:https://stackoverflow.com/questions/65893747/java-selenium-webdriver-expression-finding-dynamic-element-by-ccs-that-starts-wi

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You were close enough. You need to remove the # from the beginning of the id as # itself denotes the id attribute.


Explanation of the dynamic CSS_SELECTOR

To consider only the static part of href and data-drupal-link-system-path attributes you can use the following wildcards in :

  • $ : To indicate an attribute value ends with

  • ^ : To indicate an attribute value starts with

So the most granular css_selector would be :

div[id^='ui-select-choices-row-'][id$='" +count+ "']

Solution

Your effective line of code will be:

driver.findElement(By.cssSelector("div[id^='ui-select-choices-row-'][id$='" +count+ "']"));

Note: int is a keyword, use other names as the variable name.


References

You can find a couple of relevant detailed discussions in:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...