简体   繁体   中英

How to click elements that have generated id's if I don't know what the ID will be in Selenium

Say I have some HTML mark-up as such:

    <select id="select_titleOfSelect-1212_01" name="titleOfSelect-1212" 
        <option value="ONE"></option>
        <option value="TWO"></option>
        <option value="THREE"></option>
    </select>

Multiple of these select elements can be generated dynamically in which the number after titleOfSelect can always be different. Also the "01" will increment by 1 if there is more than one select generated on the same page.

I have been able to click on these using this:

.click('select[id^="titleOfSelect-"] option[value='ONE']')

How can I click on the 2nd, 3rd, so on.. select element on the page if there is more than one?

I'm using Javascript with Selenium

You don't search for the element based on its ID if the ID is randomly generated. You'll have to use an XPath or CSS selector and get creative.

Here's how I would click on the options:

// option 1
driver.findElement(By.xpath("//select/option[@value='ONE']")).click();

// option two
driver.findElement(By.xpath("//select/option[@value='TWO']")).click();

// etc..

Or, if you don't want to use value , you can use the index:

// click first option
driver.findElement(By.xpath("//select/option[1]")).click();

// click second option
driver.findElement(By.xpath("//select/option[2]")).click();

// click third option
driver.findElement(By.xpath("//select/option[2]")).click();

If there are multiple select elements on the page, you can try to do a contains query on the title:

//select[contains(@title, 'titleOfSelect')]/option[1]

You can use :nth-of-type() to pick which SELECT you get, eg

select:nth-of-type(2) option[value="TWO"]

would select the OPTION that contains the value 'TWO' in the second SELECT

You can simply use the findElements method to find the locator id^="titleOfSelect-" . This will return ReadOnlyCollection<IWebElement> which you can convert to a list and then target whatever index you want to target.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM