Webdriver + HtmlUnitDriver + Java + Drop down
I'm new to this forum and i'm kinda new to Selenium and everything around it. I'm a little familiar with Java, but i'm certainly not a pro
I know that there a threads like these, but still i haven't found my answer yet... Because some of them are in C# or .NET, ... .
I'm using Webdriver and HtmlUnitDriver because i don't want Selenium to pop up a browser. Everything has to be done in the background (don't wanna see anything, only 1 result (if everything went fine or not)).
Okay, that been said, here is the situation. I'm checking a website, and at some point i need to select an option from a drop down list (let's say the second option). But the problem is that this won't work...
Here is some code i'm using:
public class LoginLogout implements SeleniumTest{
private WebDriver webDriver;
@Override
public void setUp(String baseURL){
webDriver = new HtmlUnitDriver();
}
@Override
public void invoke(){
开发者_开发百科 // Login
webDriver.get("http://website");
webDriver.findElement(By.name("username")).sendKeys("Dummy123456");
webDriver.findElement(By.name("password")).sendKeys("Muddy");
webDriver.findElement(By.className("Submit")).click();
webDriver.findElement(By.name("/catalogue")).click();
webDriver.findElement(By.name("/catalogue/search/synthesis/s10")).click();
webDriver.findElement(By.name("firstYear")).findElement(By.name("2008")).isSelected();
webDriver.findElement(By.name("lastYear")).findElement(By.name("2008")).isSelected();
webDriver.findElement(By.className("Submit")).click();
webDriver.findElement(By.className("Label")).click();
}
@Override
public void tearDown(){
webDriver.close();
}
}
Where i choose the FIRSTYEAR and LASTYEAR, that's where it's going wrong...
Can someone please help me out !!! It would be great that i get this to work (with your help)
Thanks in advance
isSelected() will only tell you if the element is already selected or not, it won't actually set anything. I believe what you want to do is cast the WebElement to a Select object which provides methods for choosing select box items.
Select selectBox = (Select)webDriver.findElement(By.name("firstYear"));
selectBox.selectByValue("2008");
You can also select by Index which I find more reliable in cases where I don't actually care which value is selected but want to ensure something is chosen.
selectBox.selectByIndex(0); // chooses first item.
精彩评论