Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

selenium webdriver select element

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");

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.

like image 616
ducati1212 Avatar asked Mar 07 '12 15:03

ducati1212


People also ask

Can we use sendKeys on select elements?

sendKeys command does not work with Select elements and the only way to automate selection option is by using javascript.

How do you select an element from a dropdown by using the value of an element to be selected?

A dropdown is represented by <select> tag and the options are represented by <option> tag. To select an option with its value we have to use the selectByValue method and pass the value attribute of the option that we want to select as a parameter to that method.

How do I select html tag in Selenium?

Selenium can locate HTML elements using the built-in By. xpath() method. Once the element is located, Selenium can perform actions like clicking on links or buttons and typing text into input fields.

How do I access select options in Selenium?

New Selenium IDE We can get a selected option in a dropdown in Selenium webdriver. The method getFirstSelectedOption() returns the selected option in the dropdown. Once the option is fetched we can apply getText() method to fetch the text.


1 Answers

Thats because the Select class has this constructor:

Select(WebElement element)

See the Javadoc

So if you do something like this:

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

It should work.

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"));

returns WebElement, so thats why its working. You can also do this:

 WebElement wannabeSelect = sDriver.findElement(By.id("foo"));
 Select foo = new Select(wannabeSelect);
like image 121
Pavel Janicek Avatar answered Sep 22 '22 23:09

Pavel Janicek