未在Selenium & JAVA中选择下拉列表中的选项

voase2hg  于 2022-11-24  发布在  Java
关注(0)|答案(2)|浏览(160)

我有一个包含值的下拉列表,在尝试选择值时收到此错误消息(无法共享链接,因为它是隐藏的):

Element: [[[[ChromeDriver: chrome on WINDOWS (4aeb1bf64ec7a13956b6b0b2cf24d9ca)] -> xpath: //*[@id="Datatable_ReceiptListModel"]/tbody/tr[3]/td[10]/select]] -> xpath: .//option[normalize-space(.) = "Option 1"]]

该下拉列表的HTML为:

<select class="select-submotive inputs-table hide-in-partial" style="visibility: visible;">
        <option value="">Seleccione...</option>
            <option value="5">Option 1</option>
            <option value="6">Option 2</option>
    </select>

XPATH为:

//*[@id="Datatable_ReceiptListModel"]/tbody/tr[1]/td[10]/select

我这样做了:

Select dropdown736  = new Select(driver.findElement(By.xpath("//*[@id=\"Datatable_ReceiptListModel\"]/tbody/tr[3]/td[10]/select")));
        dropdown736.selectByVisibleText("Option 1");

我做错什么了吗?

nmpmafwu

nmpmafwu1#

试试看:

WebElement option = driver.findElement(By.CSS, "option[value='5']")
option.click()

您也可以使用Xpath按文本单击元素,如下所示:

WebElement option = driver.findElement(By.Xpath, "//option[text()='Option 1']")
option.click()
juud5qan

juud5qan2#

这段代码对我来说非常好用:

WebDriverManager.chromedriver().setup();
        WebDriver driver = new ChromeDriver();
        driver.navigate().to("file:///Users/sanders/Desktop/selenium/index.html");
        Select select = new Select(driver.findElement(By.xpath("//select[@class='select-submotive inputs-table hide-in-partial']")));
        select.selectByVisibleText("Option 1");

对于此html结构:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <select class="select-submotive inputs-table hide-in-partial" style="visibility: visible;">
        <option value="">Seleccione...</option>
            <option value="5">Option 1</option>
            <option value="6">Option 2</option>
    </select>

</body>

相关问题