In my app I have two <select> tags. The first one changes the options inside the second one and enables it in the onchange event.
When I use the Select object provided by Selenium2 it doesn't fire that event when running in IE8 (works great in FF and when I do it manually).
Select select = new Select(getElementByName(name));
element.selectByValue(value);
The first <select> changes as expected. However, the second <select> remains empty and disabled. I tried this as a workaround:
if(ie) {
WebElement select = getElementByName(name);
WebElement option = select.findElement(By.cssSelector("[value='"+value+"']"));
List<WebElement> options = select.findElements(By.cssSelector("option"));
//select the first element
options.get(0).click();
//make sure the select is focused
select.click(); //open
select.click(); //close
Keyboard keyboard = getWebDriver().getKeyboard();
for(int i = 0; i < options.size() && option.getAttribute("selected") == null; i++) {
keyboard.pressKey(Keys.DOWN);
//note: if i do a Thread.sleep(100); here, it works more consistently, but still not 100%
}
} else {
// Do the above snippet
}
but now I get inconsistent results. The desired <option> always gets selected, while only sometimes does the event get fired.
Obviously the best option is getting the Select to work in IE8. Has anyone else seen this issue? Seems like a bug in Selenium2. Is there a known workaround for this?
After talking with some of the Selenium folk in the #selenium IRC chat room I settled on this fix:
WebElement selectElement = getElementByName(name);
Select select = new Select(selectElement);
element.selectByValue(value);
if(usingIE) {
webDriver.executeScript("$(arguments[0]).fireEvent('change');", selectElement);
}
Am using below code to select a value in 'Country' list (once 'Country' value is selected, corresponding 'State' list is loading):
WebElement selectCountry = driver.findElement(By.id("country"));
List<WebElement> options = selectCountry.findElements(By.tagName("option"));
for(WebElement option : options){
if(option.getText().equalsIgnoreCase("India")){
option.click();
break;
}
}
Note - This select operation takes much more time IE when compare to FF. You may need to increase command timeout time using driver.manage().
It looks like you are already implementing the SelectElement class so have you tried this
WebElement element = getElementByName(name);
element.FindElement(By.CssSelector("option[value='" + value + "']").Select();
Related
I am trying to select an option from a drop down. If there is no drop down options are visible then script execution should continue.
Please find my code below -
List<WebElement> drop_down_options = driver.findElements(By.className("mat-option"));
if (drop_down_options.size() == 0) {
System.out.println("drop down options are not visible");
} else {
drop_down_options.get(0).click();
}
Here It is taking long time to execute the script if there are no drop down option is present. In my web page some of the drop downs are disabled (which has default value) so I don't want to click or select the option.
But it stuck for some times(more than 4 minutes) in the first line of the code which I mentioned above.
Even if there are element is not visible it waits for some time,so that my script takes time to execute.
I have tried by
isDisplayed(), isEnabled() ,isPresent
try catch
Please give me a solution to continue my script if there are no elements visible in the page
Updated comment:
I have tried all the solutions as mentioned below
1.In first option Select select = new Select( drop_down_options); shows me error saying that "cast argument drop_down_options to WebElement"
2.where as in the second option getText() returns place holder value and other help text message near the input field
GetAttribute() returns null
tried with below code but same result which takes time to exceute if there are no options
for (int d = 0; d < dropdowns.size(); d++) {
Thread.sleep(1000);
System.out.println("----------------" +dropdowns.get(d).getAttribute("value"));
System.out.println("----------------" +dropdowns.get(d).getText());
dropdowns.get(d).click();
Thread.sleep(1000);
WebDriverWait wait=new WebDriverWait(driver,10);
wait.until(ExpectedConditions.visibilityOfAllElements(drop_down_options));
try{
if (drop_down_options.size()==0) {
drop_down_options.get(0).click();
}
}catch(Exception e)
{
e.printStackTrace();
}
If your DOM is using options tag for drop down then try below :
List<WebElement> drop_down_options = driver.findElements(By.className("mat-option"));// Assuming class name is from parent tag.
Select select = new Select(drop_down_options);
List<WebElement> allOptions = select.getOptions();
option 2
try to get default value of dropdown using gettext() or getattribute()
you can check attribute value is =="DISABLE" don't click.
Or you can get default value and check if it is not null then only perform click action
Option 3
try and catch {} it should work if not working put your work and details. Juts a note Catch should not have return statements to continue after your exception.
I use cssselector with Keys class. But the value is not selected
browser.findElement(By.cssSelector("input[id='loadingPort']")).sendKeys("Odes", Keys.DOWN, Keys.ENTER);
I want to select the value Odessa from drop down list:
I'm not sure how the website is populating that dropdown, but maybe you could enter your text and then select the first option like this:
browser.findElement(By.cssSelector("input[id='loadingPort']")).sendKeys("Odes");
browser.findElement(By.cssSelector("input[id='loadingPort']")).findElements(By.tagName("option")).get(0).click()
/** OR */
browser.findElement(By.cssSelector("input[id='loadingPort']:first-child")).click()
Sorry, I'm not familiar with java or cssSelectors... just Selenium. If you can clean up that code, that should work if the website is dynamically adding options to the dom.
One more using xpath:
browser.findElement(By.xpath("input[#id='loadingPort']/option[1]")).click()
There are multiple ways to handle dropdown value
- dropdown.selectByVisibleText("Text");
- dropdown.selectByIndex(2); (Index starts with zero always in list)
- dropdown.selectByValue(“Text”)
Sample Code:
Select oSelect = new Select(driver.findElement(By.cssSelector("input[id='loadingPort']")));
// Select option (Odessa(UKR))
oSelect.selectByVisibleText("Odessa(UKR)"); // Using sleep command so that changes can be noticed
Thread.sleep(2000);
// : Select option 'using Index
oSelect.selectByIndex(1);
Thread.sleep(2000);
// Print all the options for the selected drop down and select one option of your choice
// Get the size of the Select element
List<WebElement> oSize = oSelect.getOptions();
int iListSize = oSize.size();
// Setting up the loop to print all the options
for(int i =0; i < iListSize ; i++){
// Storing the value of the option
String sValue = oSelect.getOptions().get(i).getText();
// Printing the stored value
System.out.println(sValue);
// Putting a check on each option that if any of the option is equal to 'Africa" then select it
if(sValue.equals("Odessa(UKR)")){
oSelect.selectByIndex(i);
break;
}
}
I want to automate drop down menu using Selenium web driver using Java, but the HTML page has <option disabledselected>----</option> (Ref to attached screenshot)
I want to select 2nd menu item from drop down. I've tried many things but every time I'm get an error message.
1st Approach - using ByVisibleText:
public void selectHomeCommunity(String name){
Select hmecomm= new Select(hmecommdropdown);
hmecomm.selectByVisibleText(name);
}
public <Webelement> SelfRegistrationPage Community(String pass) {
// TODO Auto-generated method stub
enterPassKey(pass);
System.out.println("Entered into Community method");
pressGoBtn();
}
2nd Approach - JavascriptExecutor:
((JavascriptExecutor)driver).executeScript("document.getElementById('hmecommdropdown').options.item(0).click().;");
3rd Approach - getFirstSelectedOption:
String selectedLabel = new Select(driver.findElement(By.id("CommunityDropdown"))).getFirstSelectedOption().getText();
Every time I'm getting same error as:
waiting for visibility of [[ChromeDriver: chrome on XP
(9a6751455dba60b65479430ff8f9aa00)] -> id: CommunityDropdown]
If the dropdowns are from a language such as angular then using Select may not work. My suggestion is us seleniums click operations.
Click the dropdown to open it
Use driver.findElements to find all the webelements for the options inside the dropdown
Iterate through the elements and pull out the text in the elements. When you find the text you are expecting perform the click
Something like the following may be useful:
public void clickDropdownOption(WebDriver driver, String option) throws Exception{
waitForDropdownMenuToBeVisible(driver);
WebElement dropdownMenu = driver.findElement(dropdownMenuLocator);
List<WebElement> optionElements = dropdownMenu.findElements(dropdownOptionLocator);
for(int i=0; i < optionElements.size(); i++){
if(optionElements.get(i).getText().equals(option)){
click(driver, optionElements.get(i));
waitForDropdownMenuToBeinvisible(driver);
return;
}
}
throw new Exception("Dropdown option " + option + " was not found");
}
Obviously if it is a normal HTML dropdown then use the conventional approach
hey i am writing a test case in selenium, the test is based on a shopping website ( http://www.beechtree.pk/ ) and what i want to check in my test is if the size for the product select is available or not. the sizes that are not available are gred out on the website so i understand that they are not clickable anymore. I have tried using isEnabled and isDisplayed condition to check if its clickab;e but they don't work.
ps: i want to CHECK if its clickable(size is available) so that if it is not, my program can choose another size to carry on with the procedure (it is currently choosing randomly) so i don't want to wait for it to become clickable.
isEnabled and isDisplayed should work for you. Can you check whether you are selecting the element properly.
Can you print the text of the button.
Dummy code:
public class Test{
public static void main(String[] args) {
// TODO Auto-generated method stub
System.setProperty("webdriver.chrome.driver", "C:\\Selenuim\\chromedriver2.3.exe");
WebDriver driver = new ChromeDriver();
try{
driver.get("http://register.rediff.com/register/register.php");
Thread.sleep(2000);
WebElement e = driver.findElement(By.name("btnemail"));
boolean actualValue = e.isEnabled();
if (actualValue)
System.out.println("Button is enabled");
else
System.out.println("Button is disabled");
Thread.sleep(2000);
}
catch(Exception ex){
System.out.println("Exception " + ex.getMessage());
}
finally{
driver.close();
driver.quit();
}
}
}
As i see you can try to get the class attribute and check if it contains disabledSwatch.
If you need to check only on the sizes that are available then why not use a css selector like:
span[class='swatch']
You can use this selector to search elements and click random from them.
Xpath alternative:
//*[#class='swatch']
or
//*[#class='swatch']/..
To get all the clickable elements:
List<WebElement> elms = driver.findElements(By.cssSelector("span.swatch:not(.disabledSwatch)"))
To get all the non clickable elements:
List<WebElement> elms = driver.findElements(By.cssSelector("span.swatch.disabledSwatch"))
To get a random element and check if it's clickable by testing the cursor:
List<WebElement> elms = driver.findElements(By.cssSelector("span.swatch"));
boolean disabled = elms.get(i).getCssValue("cursor") != "pointer";
To get a random element and check if it's clickable by testing the class:
List<WebElement> elms = driver.findElements(By.cssSelector("span.swatch"));
boolean disabled = elms.get(i).getAttribute("class").contains("disabledSwatch");
I would suggest that instead of checking random sizes to see if they are available, you would check all the sizes to see if they are available or not.
From the site, the size is in a SPAN element. This size is not available, note the disabledSwatch class on the element.
<span id="swatch11" class="swatch disabledSwatch" onclick="colorSelected('attribute133','11','','8')">8</span>
^^^^^^^^^^^^^^
This size is available, the disabledSwatch class is not present.
<span id="swatch14" class="swatch" onclick="colorSelected('attribute133','14','','10')">10</span>
Using this info, we can pull all the sizes and remove those that are not available. This will get us two lists, one with only the sizes that are available and another list with the sizes that are unavailable. Those elements contain text that indicates the size.
Using all this info, the code below pulls all the elements, separates them into available vs unavailable elements, and then pulls the size info from each element and stores those in two lists, availableSizes and unavailableSizes. From there you can print the lists or verify if certain sizes are available or not, etc.
List<WebElement> unavailableElements = driver.findElements(By.cssSelector("div.swatchesContainer span.swatch.disabledSwatch"));
List<WebElement> availableElements = driver.findElements(By.cssSelector("div.swatchesContainer span.swatch"));
availableElements.removeAll(unavailableElements);
List<String> unavailableSizes = new ArrayList<String>();
List<String> availableSizes = new ArrayList<String>();
for (WebElement e : unavailableElements)
{
unavailableSizes.add(e.getText());
}
for (WebElement e : availableElements)
{
availableSizes.add(e.getText());
}
Wouldn't something like this work?
List<WebElement> sizes = new ArrayList<WebElement>();
for(WebElement size : sizes) {
if(size.isDisplayed() && size.isEnabled()) {
size.click();
break;
}
}
I have a HTML code. The thing is that the option names contain lots of spaces until the tags are closed.
<SELECT NAME="auth" id="auth" Size=1 onChange="updatePageState()">
<OPTION value="0">Open System
</option>
<OPTION value="1">WEP
</option>
<OPTION value="2">WPA
</option>
<OPTION value="3">WPA2
</option>
I want to check that some option is selected in the dropdown box by using selenium in java. This is my code:
try {
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.textToBePresentInElementValue(((By.xpath("//select [#id='auth']/option['" + Authen + "']"))), Authen));
System.out.println("Authentification is correct");
} catch (Exception x) {
System.out.println("Authentification is incorrect");
x.printStackTrace();
}
where "Authen" is a variable read from a file which corresponds to the options in the dropdown box.
I get the following error message:
org.openqa.selenium.TimeoutException: Timed out after 20 seconds
waiting for text ('WPA2') to be the value of element located by
By.xpath: //select [#id='auth']/option['WPA2']
Any help on how to check if that string contains partial text? I cannot use the method .contains because it's of type boolean and .textToBePresentInElementValue needs to have the second attribute as type String.
Maybe it is easier to select the webelement with a less complex #FindBy expression and then wrap the element in a Select which provides a method to get the first selected option. You then can do your comparison.
Take a look at:
https://selenium.googlecode.com/git/docs/api/java/org/openqa/selenium/support/ui/Select.html
Use the xpath containts() function to find the element. Such as
//select[#id='auth']/option[contains(text(),'Open System')]
You can check each option through this:
WebDriver driver;
ArrayList<String> valuesToCheck;
Select selectBox = new Select(driver.findElement(By.name("auth")));
List<WebElement> boxOptions = selectBox.getOptions();
int i = 0;
ArrayList<boolean> isPresent = new ArrayList<boolean>();
for(String val : valuesToCheck)
{
for(WebElement option : boxOptions)
{
selectBox.selectByIndex(i);
if(selectBox.getFirstSelectedOption().getText().equals(valueToCheck.get(i)))
{
isPresent.get(0) = true;
}
}
if(isPresent.get(0)!=true)
{
isPresent.get(0)=false;
}
}
this would return an array of booleans that check if the values you were looking for were present inside of the select statement.
its a little bit of a workaround, but i think it would do the job.
Also, i couldn't find documentation so this is coming out of pure opinion and could potentially not be fact, but doesn't the value attribute supposed to specify the text? that could be your current problem.