简体   繁体   English

硒选择无法找到选项

[英]Selenium Select Can't locate options

I am having an issue when I locate and assign a Select object grabbing its options, probably due to some of the wonky HTML on the page. 当我找到并分配一个选择对象以抓取其选项时遇到问题,这可能是由于页面上一些奇怪的HTML所致。 Here is the HTML of the Select and its options: 这是Select及其选项的HTML:

<select>
<option selected="" val="1">1</option>
<option val="2">2</option>
<option val="3">3</option>
<option val="4">4</option>
<option val="5">5</option>
...
</select>

The select is located using XPath as such: .//*[@id='employeeTable_paginate']/div/select 使用XPath这样可以定位选择: .//*[@id='employeeTable_paginate']/div/select

I am wondering if it isn't able to locate the options since the values are referred to as vals in the HTML? 我想知道是否无法找到选项,因为这些values在HTML中称为vals I tried the following code to see if it would get the Options: 我尝试了以下代码,看是否可以获得选项:

for (WebElement option : select.getOptions()) System.out.println(option);

but it does not print anything. 但它不会打印任何内容。 Additionally, if I try to select an option by index, it says it can not locate option with that index. 另外,如果我尝试按索引选择一个选项,它说它找不到该索引的选项。

selectByValue would definitely not work in that case. 在这种情况下,selectByValue绝对不起作用。 If you go to the implementation of Select , you can see that selectByValue() uses xpath to find the value field. 如果转到Select实现 ,则可以看到selectByValue()使用xpath查找value字段。 The good news is that it's an easy fix. 好消息是,这很容易解决。

For your case, you'll want to find the single value (searching for val instead), and select it. 对于您的情况,您需要查找单个值(改为搜索val ),然后选择它。

WebElement option = element.findElement(By.xpath(
        ".//option[@val = '" + value + "']"));

if (!option.isSelected())
{
    option.click();
}

I'm not sure why selectByIndex doesn't work, can you check the count of select.getOptions() ? 我不确定为什么selectByIndex不起作用,可以检查select.getOptions()的计数吗? It's always possible the select object is just incorrect. 选择对象总是有可能是错误的。

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

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