Searching and Selecting value from dropdown using selenium Webdriver - selenium

I want to know how to select a specific value from dropdown from a pool of values.
My logic is
1.Open the page
2.Fetch all the values from dropdown in list
3.Use a loop
4.Look for that value
5.If the value is not there,select the value x
For me it is saying No such Element Exception
Is it do we need to focus on that element first
In my code i want to select Nextran Corporation
Below is my code
#Test(dependsOnMethods={"go2personalsettings"})
void setru()
{
driver.switchTo().frame("contentFrame");
Select rudropdown=new Select(driver.findElement(By.id("DefaultOrganisationDropDown")));
List<WebElement> drop=rudropdown.getOptions();
int e=drop.size();
String actual_ru="999425, NEXTRAN CORPORATION - JACKSONVILLE";
for(int i=0;i<e;i++)
{
String expected_ru=drop.get(i).getText();
if(!expected_ru.equals(actual_ru))
{
rudropdown.selectByValue(actual_ru);
}
}

Try This:
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//li[contains(text(),'" + ElementValue + "')]")));
WebElement webElement = driver.findElement(By.xpath("//li[contains(text(),'" + ElementValue + "')]"));
webElement.click();

The logic in your code doesn't match what you stated was your intent. You stated that you want to select a particular value from the dropdown, if it exists. If it doesn't, select value 'x'. Your code doesn't ever select value 'x' so I'm not sure what 'x' is but you can fill that in below. Basically the code attempts to select the expected value. If that expected value does not exist, it will throw an exception which is caught and then 'x' is selected. If it does exist, the value is selected and selecting 'x' is skipped.
driver.switchTo().frame("contentFrame");
Select rudropdown = new Select(driver.findElement(By.id("DefaultOrganisationDropDown")));
String actual_ru = "999425, NEXTRAN CORPORATION - JACKSONVILLE";
try
{
rudropdown.selectByValue(actual_ru);
}
catch (NoSuchElementException e)
{
// expected value does not exist, select the value x instead
rudropdown.selectByValue("x");
}

Related

How to perform click on a string value?

I want to click a variable value which is stored in a string and below is my code.
OrderConfirmationData orderConfirmationData= (OrderConfirmationData)Serenity.sessionVariableCalled("OrderConfirmationData");
int maxtries=0;
System.out.println("Order is available in NTI" + EfloristConstants.lastname.get());
List<WebElement> recordcount = getDriver().findElements(By.xpath("//table[contains(#id,'ctrlDWController1_DWDetails1_gvNTI')]/*/tr[not(contains(#style,'bold'))]"));
int j=16;
for(int i=1;i<=recordcount.size();i++) {
j=j*i;
String record = "(//table[contains(#id,'ctrlDWController1_DWDetails1_gvNTI')]/*/tr[not(contains(#style,'bold'))]/td)["+j+"]";
String recipientname= element(By.xpath(record)).getTextValue();
if(recipientname.equals(orderConfirmationData.getShipFirstName() != null)) {
System.out.println("Order is available ");
}
j=16;
}
want to click on the recipientname when the, if the condition matches i.e want to perform click inside the If condition.
Add the below line in if condition:
element(By.xpath(record)).click()

Based on my previous qu-How to perform some actions on each value from a drop down using selenium java?

Now I want to select first value from a drop down then perform some actions on it, then I want to select second value from the same drop down and perform the same action on it.
Here is my code:
WebElement bldgs=Fn_GetWebElement(CreateSSIObject.getProperty("Bldgselect"));
Select Bldg_select=new Select(bldgs);
List<WebElement> dropdownvalues = Bldg_select.getOptions();
int count=dropdownvalues.size();
System.out.println("Total number of values are :"+count);
for(int i=1;i<count;i++) {
if(dropdownvalues.get(i).isEnabled()) {
Bldg_select.selectByIndex(i);
System.out.println("Not Working :"+i);
waitForWebPagetoLoad(2000);
WebElement search_BTN=Fn_GetWebElement(CreateSSIObject.getProperty("search_Btn"));
fn_Click(search_BTN);
WebElement add_VEND=Fn_GetWebElement(CreateSSIObject.getProperty("add_vendors"));
fn_Click(add_VEND);
WebElement vendorName=Fn_GetWebElement(CreateSSIObject.getProperty("vendor_Name"));
fn_Click(vendorName);
vendorName.sendKeys(vendor);
waitForWebPagetoLoad(5000);
WebElement search_BTN1=Fn_GetWebElement(CreateSSIObject.getProperty("search_Btn"));
fn_Click(search_BTN1);
WebElement selectVendor=Fn_GetWebElement(CreateSSIObject.getProperty("select_Vendor"));
fn_Click(selectVendor);
WebElement addToSite=Fn_GetWebElement(CreateSSIObject.getProperty("AddTo_Site"));
fn_Click(addToSite);
}
}
here I am seaching for an element(basically drop down id) and then selecting each value with selectbyindex with i for loop. and then I am clicking on a button and performing some more actions on it. Now it is selecting only first value and doing all above stuff. But it is not going back in for loop to select 2nd value and performs same steps.
I don't quite understand your problem butI can see 2 issues that may be adding to confusion.
Index should 0 based
Your loop is starting with i set to 1. As lists are zero based indexes, you should start at 0
Referencing stale elements??
You are extracting the dropdown values outside of the loop and then referencing these within the loop using index. However, you are performing a lot of actions and events within each iteration.
You may be better extracting the values again within each iteration to ensure all your references are up to date and have not gone stale.
Can you please try below solution? I am not sure what action you are tryig to execute based on selection but I think below code solve your problem.
Select drpCountry = new Select(driver.findElement(By.name("Locator")));
List <WebElement> elementCount = drpCountry.getOptions();
int iSize = elementCount.size();
for(int i =0; i<iSize ; i++)
{
String sValue = elementCount.get(i).getText();
System.out.println(sValue);
drpCountry.selectByIndex(i);
if(sValue.equalsIgnoreCase("Selection1")){
//code to be executed if condition1 is true
}else if(sValue.equalsIgnoreCase("Selection2")){
//code to be executed if condition2 is true
}
else if(sValue.equalsIgnoreCase("Selection3")){
//code to be executed if condition3 is true
}
else{
//code to be executed if all the conditions are false
}
}

Xpath con-cat is possible with reference to List<WebElement> object in selenium?

Scenario with Example:
10 Different Row in Table (e.g. //a[#class='*******'] ).
Need to Retrieve different Value from each Row
Retrieving it using List
In given example, Temp1 getting executed and iterate as required, As information need to retrieve from the same and got it through getAttribute(" ").
Need to retrieve Temp2 value which is dependent on object findList. findSubInfo is having Following Siblings from mainList. Its only addition on following siblings in to List exa.(findList).
Issue is :
If I execute 1st provision, as independent node, It always retrieve first row's value. (Which is Obvious)
If I execute 2nd provision, with xpath + List object using con-cat it throws xpath Syntax issue.
Question :
How can retrieve all information from object's siblings, where object List<WebElement> findList is pointing ?
Trial :
By mainList = By.xpath("//a[#class='*******']");
By findSubInfo = By.xpath("//a[#class='*****']//following::div[#class='****']");
List<WebElement> findList = driver.findElements(mainList);
for (WebElement webElement : findList ) {
if (webElement.isDisplayed()) {
String temp1= "Info1:" + webElement.getAttribute("ng-href");
String temp2= "Info2: " + driver.findElement(findSubInfo).getText();
}
}
OR
String mainList "//a[#class='*******']";
String findSubInfo = "//following::div[#class='****']";
List<WebElement> findList = driver.findElements(By.xpath(mainList));
for (WebElement webElement : findList ) {
if (webElement.isDisplayed()) {
String temp1= "Info1:" + webElement.getAttribute("ng-href");
String temp2= "Info2: " + driver.findElement(By.xpath(webElement + findSubInfo )).getText();
}
}
Exception Details:
SyntaxError: Failed to execute 'evaluate' on 'Document': The string
'[[ChromeDriver: chrome on XP (3208ef0a2ffd32812c33e159291eebe4)] ->
xpath: //a[#class='noDecoration
addPointer']]//following::div[#class='assignedAccountMasterAddress']'
is not a valid XPath expression.
If you want to search for element with related XPath starting from current element (webelement), try
# Note that it should start with the dot
String findSubInfo = "./following::div[#class='****']";
# use webElement.findElement instead of driver.findElement. No XPath concatenations needed
String temp2= "Info2: " + webElement.findElement(By.xpath(findSubInfo)).getText();

Dropdown duplicate value automation using Selenium

How to check the duplication of values in a checkbox using Selenium Webdriver
something like the below one will work if both the options have same value
public boolean isSelectOptionsRepeating(WebElement dropdown)
{
Select s = new Select(dropdown);
List<WebElement> list = s.getOptions();
Set<String> listNames = new Hashset<String>(list.size());
for (WebElement w : list) {
listNames.add(w.getText().trim());
}
if(list.size()== listNames.size())
return true;
else
return false;
}
You can store the values of drop down in String array and
traverse string array and use Hashmap for storing the values from the dropdown and if duplicate occurs increement the count by one
voila......you would know the the Values with its count, if count > 1. Duplicate
for reference : Java Beginner - Counting number of words in sentence

How to verify character count of text field?

I want to check the number of characters I can insert in a text field, and was thinking of using 'for loop' but it would not help as Selenium tries to insert more than required character the field will not accept but test goes on without any failure, so is there a way to get character count of the text field?
Would this work?
final String myLongString = "Something horrrrribly looooong";
final int longStringLength = myLongString.length();
// assuming driver is a healthy WebDriver instance
WebElement elem = driver.findElement(By.id("myInput"));
elem.sendKeys(myLongString);
// it's possible that you'll first need to lose focus on elem before the next line
int realLength = elem.getValue().length();
assertEquals(longStringLength, realLength);
Using Protractor I captured the actual text in the field and then did a forloop to count each letter.
element(by.css('elementPATH')).getAttribute('value').then(function(words){
//forloop to count each word
var x = 0
for(var i = 0; i < words.length; i++) {
x = x + 1;
};
//check condition
expect(x).toBe(200);
return true;
});
Let me know if this helps.