如果我不知道Selenium中的ID将如何单击已生成ID的元素

说我有一些HTML标记,例如:

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

多个选择元素可以动态生成 其中titleOfselect之后的数字始终可以不同。 如果在同一页面上生成多个选择,则“ 01”也将增加1。

我已经可以使用以下命令单击它们:

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

如何单击第二,第三等等。如果页面上有多个元素,请选择页面上的元素?

我在Selenium中使用Javascript

chengwei8520 回答:如果我不知道Selenium中的ID将如何单击已生成ID的元素

如果随机生成ID,则不会根据其ID搜索该元素。您必须使用XPath或CSS选择器并发挥创造力。

这是我点击选项的方式:

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

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

// etc..

或者,如果您不想使用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();

如果页面上有多个select元素,则可以尝试对标题进行contains查询:

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

您可以使用:nth-of-type()来选择要获得的选择,例如

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

将在第二个SELECT中选择包含值“ TWO”的OPTION

,

您可以简单地使用findElements方法来找到定位符id^="titleOfSelect-"。这将返回ReadOnlyCollection<IWebElement>,您可以将其转换为列表,然后定位要定位的任何index

本文链接:https://www.f2er.com/3141772.html

大家都在问