硒webdriver选择元素 [英] selenium webdriver select element

查看:100
本文介绍了硒webdriver选择元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的网站上有一个选择控件.我正在使用页面对象与页面进行交互.如果我愿意(在我的类下是前两行,在方法中是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>

让我说我可以解决我的问题,但我不明白为什么 normal 路径不起作用.

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

因此,如果您执行以下操作:

So if you do something like this:

@FindBy(id="foo")
private WebElement wannabeSelect;
Select realSelect = new Select(wannabeSelect);
realSelect.selectByValue("myValue");

应该可以.

顺便说一句,在替代方法"中,我使用的方法与您相同,因为当我需要选择对象时,我不想投射新的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);

这篇关于硒webdriver选择元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆