简体   繁体   English

如果我不知道 Selenium 中的 ID 是什么,如何单击已生成 ID 的元素

[英]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:假设我有一些 HTML 标记,如下所示:

    <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.可以动态生成多个 select 元素,其中titleOfSelect之后的数字始终可以不同。 Also the "01" will increment by 1 if there is more than one select generated on the same page.如果在同一页面上生成多个 select,“01”也会增加 1。

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?如果页面上的元素不止一个,我如何点击第 2、3 等等.. select 元素?

I'm using Javascript with Selenium我正在使用 Javascript 和 Selenium

You don't search for the element based on its ID if the ID is randomly generated.如果 ID 是随机生成的,则不会根据其 ID 搜索元素。 You'll have to use an XPath or CSS selector and get creative.您必须使用 XPath 或 CSS 选择器并发挥创意。

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:或者,如果您不想使用value ,则可以使用索引:

// 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查询:

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

You can use :nth-of-type() to pick which SELECT you get, eg您可以使用:nth-of-type()来选择您得到的 SELECT,例如

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

would select the OPTION that contains the value 'TWO' in the second SELECT将 select 包含在第二个 SELECT 中的值“TWO”的 OPTION

You can simply use the findElements method to find the locator id^="titleOfSelect-" .您可以简单地使用findElements方法来查找定位器id^="titleOfSelect-" This will return ReadOnlyCollection<IWebElement> which you can convert to a list and then target whatever index you want to target.这将返回ReadOnlyCollection<IWebElement> ,您可以将其转换为列表,然后定位您想要定位的任何index

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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