selenium webdriver 选择元素 [英] selenium webdriver select element
问题描述
我的网站上有一个选择控件.我正在使用页面对象与页面进行交互.如果我这样做(在我的类下的前 2 行和我的方法中的 selectByValue
)
I have a select control on my site. I am using page objects to interact with the page. If I do (with the first 2 lines under my class and the selectByValue
in my method)
@FindBy(id="foo")
private Select foo;
foo.selectByValue("myValue");
它以空指针失败.我也试过没有 @FindBy
.
It fails with a null pointer. I also tried without the @FindBy
.
现在,如果我在我的方法中执行此操作,一切正常并选择正确的项目
Now if I do this in my method it all works fine and selects the correct item
Select foo = new Select(sDriver.findElement(By.id("foo")));
foo.selectByValue("myValue");
这是该控件的实际网页片段(经过编辑以保护无辜者)
Here is the actual web snippet for that control (edited to protect the innocent)
<select id="foo" name="service_name">
<option selected="selected" value="one">one</option>
<option value="two">two</option>
<option value="three">three</option>
</select>
让我说我有一个解决我的问题的方法但是我不明白为什么正常"路径不起作用.
Let me say that I have a work around for my issue but I don't get why the "normal" path is not working.
推荐答案
那是因为 Select
类有这个构造函数:
Thats because the Select
class has this constructor:
Select(WebElement element)
请参阅 Javadoc
所以如果你这样做:
@FindBy(id="foo")
private WebElement wannabeSelect;
Select realSelect = new Select(wannabeSelect);
realSelect.selectByValue("myValue");
它应该工作.
顺便说一句,我在解决方法"中使用与您相同的方法,因为我不想在需要 Select 对象时转换新的 WebElement 对象.但不管怎样,
BTW, I am using the same approach as you in the "workaround" because I dont wanna cast new WebElement object when I need Select object. But anyways, the
sDriver.findElement(By.id("foo"));
返回 WebElement
,这就是它起作用的原因.你也可以这样做:
returns WebElement
, so thats why its working. You can also do this:
WebElement wannabeSelect = sDriver.findElement(By.id("foo"));
Select foo = new Select(wannabeSelect);
这篇关于selenium webdriver 选择元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!