Can't get option list from a select - java

here is my html:
The solution was simple, i put a select object and get thougth the method getAllOptions but it doesn't work and know i'm doing this to get not the id (value) i want the option's text:
WebElement optionElement = driver.findElement(By.xpath("//select[#id=\"" + selectToFind + "\"]/option["+ randomItemIndex + "]"));
optionSelected = optionElement.getText();
being selectToFind the select's id which is FORM_FIELD_EndUser_planning and randomItemIndex which comes from a method that returns a random value taking in account the size of options in the list:
List <WebElement> itemsInDropdown = driver.findElements(By.xpath("//select[#id=\""+ selectToFind + "\"]/option"));
All tries of the object optionElement (like .getText()) returns "" and i'm stuck with this.

I think you can use
option.getAttribute("innerText");
or
option.getAttribute("innerHTML");
Or expand your Select element (by click) and then try to get a text of options because .getText() method returns only visible text

Related

Select value from drop down autocomplete

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;
}
}

Creating PayPal buy now button with multiple products (java sdk)

I am having difficulty creating a PayPal "Buy Now" button with the Java paypal-sdk. Single products seem to work okay. I would like the button to go to the checkout page with the product prices, descriptions and item numbers and NOT be editable. Here is a look at my code. First I create my array of button vars. (This code snipped is in Groovy)
List<String> buttonVarList = new ArrayList<String>()
int count = 1
int size = priceMap.size()
double totalPrice = 0.0
for (Map.Entry<String, PriceInfo> entry : priceMap.entrySet())
{
String skuKey = entry.getKey()
PriceInfo priceInfo = entry.getValue()
String itemNum = (size > 1) ? "_" + String.valueOf(count) + "=" : "="
Product product = Product.findByProductCode(skuKey)
buttonVarList.add("item_name" + itemNum + product.productName)
buttonVarList.add("item_number" + itemNum + skuKey)
buttonVarList.add("amount" + itemNum + priceInfo.unitPrice)
buttonVarList.add("quantity" + itemNum + priceInfo.qty)
totalPrice += priceInfo.totalPrice
count++
}
buttonVarList.add("currency_code=" + currency)
buttonVarList.add("business=" + grailsApplication.config.grails.paypal.email)
buttonVarList.add("subtotal=" + totalPrice)
buttonVarList.add("notify_url=" + grailsApplication.config.grails.paypal.notifyPaypal)
buttonVarList.add("return=" + grailsApplication.config.grails.paypal.successPaypal)
buttonVarList.add("cancel_return=" + grailsApplication.config.grails.paypal.cancelPaypal)
Payment payment = createTransaction(null, priceMap, request.getRemoteAddr(), "PAYPAL")
buttonVarList.add("transactionId=" + payment.transactionId)
buttonVarList.add("buyerId=" + payment.buyerId)
return paypalApi.createButton(buttonVarList)
After I create the button var list, I create my encrypted button.
BMCreateButtonRequestType requestType = new BMCreateButtonRequestType();
requestType.setButtonType(ButtonTypeType.fromValue("BUYNOW"));
requestType.setButtonCode(ButtonCodeType.fromValue("ENCRYPTED"));
requestType.setButtonLanguage("en");
requestType.setButtonVar(buttonVarList);
With BUYNOW as the button type, the button will work for single products, but for multiple products (item_name_1, item_name_2 variables etc), it seems to not recognize the products and the checkout page has the price and description editable. From the documentation I can see this is likely because it does not recognize the additional products "If this variable is omitted, buyers see a field in which they can enter the item name."
I have also tried using the CART button type, which works for single products, but for multiple products returns the error 11929 "A cart button must have an item name and amount specified."
Is this the correct way to specify multiple products in the checkout cart? I feel like I must be missing something simple. Thanks for the help.
EDIT 1:
I have tried adding the cart upload option "upload=1" with an unencrypted cart button. If I then remove the underscores from the item button vars in code, then re-add them by hand to the generated button (and remove add=1 which upload does not seem to override..) it seems to work. I obviously can't do this since I need encrypted buttons..but at least I can see there is a way to get it work. Perhaps I should ditch the Paypal Java Button Manager API?
This API looks to be very confusingly documented, but I think the PayPal BuyNow buttons, regardless of how you generate them, are intended for single item purchases - that's their entire point:
https://www.paypal.com/bm/cgi-bin/webscr?cmd=_singleitem-intro-outside
Even with an add to cart button - the intent is still that it is a single item you are adding to the cart:
https://www.paypal.com/bm/cgi-bin/webscr?cmd=_shoppingcart-intro-outside
You'd then go to your cart and complete purchase there - but both add to cart and buy now look to me to be designed for single items. Once you get to the cart - then you are dealing with multiple items.
I don't think that is possible , but you can always create a Buttons for single purchases for a pack of all your multiple product that are eligible for one checkout
But still the best and flexible solution is to use Buttons for shopping cart purchases

Java: showing the output of a separate for loop as an extra column shown in a console

Bit of context...
In my project I have one embedded for loop that outputs data whereby for each category show the item and within each item show its property so in reality the output I generated is 3 columns of data in the console (headings: Category/Item/Property) The for loop to show this data looks like this (Variables are set earlier on in the method):
for... (picks up each category)
for...(picks up items in category)
for (String propertyName : item.getPropertyNames()) {
out.println(category.getName() + "\t"
+ itemDesc.getName() + "\tProperty:"
+ propertyName);
}
}
}
The purpose of the project is to provide a more dynamic documentation of the properties of set components in the system. (The /t making it possible to separate them in to individual columns on a console and even in a file in say an excel spreadsheet should I choose to set the file on the printstream (Also at the start of this method.))
The Problem
Now for the problem, after the for loops specified above I have generated another for loop separate from the data but shows the list of all the functions and operators involved in the components:
//Outside the previous for loops
for (Function function : Functions.allFunctions) {
out.println(function.getSignature());
}
What I want is to set this list as the 4th column but the positioning of the for loop and the way it is set leaves it fixed on the first column with the categories. I cant add it after property names as the functions are more generic to everything in the lists and there maybe repetitions of the functions which I am trying to avoid. Is there a way to set it as the forth column? Having trouble finding the sufficient research that specifies what I am looking for here. Hope this makes sense.
One solution, if the total amount of output is small enough to fit in memory, is to simply save all the data into an ArrayList of String, and output it all at the very end.
List<String> myList = new ArrayList<String>();
for... (picks up each category)
for...(picks up items in category)
for (String propertyName : item.getPropertyNames()) {
myList.add(category.getName() + "\t"
+ itemDesc.getName() + "\tProperty:"
+ propertyName);
}
}
}
int i = 0;
// Here we assume that the total lines output by the previous set of loops is
// equal to the total output by this loop.
for (Function function : Functions.allFunctions) {
out.println(myList.get(i) + "\t" + function.getSignature());
i++;
}

QTP Script | how to get object of some open window just using its class type, like JavaWindow, without specifying its title

I want my code to b as dynamic as possible, here is my code
Set buttonDesc = Description.Create()
buttonDesc("Class Name").Value = "JavaButton"
Set reqButton = JavaWindow("AKAM Application").ChildObjects(buttonDesc)
text = reqButton(1).GetROProperty("label")
JavaWindow("AKAM Application").JavaButton(text).Click
here, in line 1 and 2, I have declared a property so that i can click on button using its index (1) without specifying its title, I want to do the same for the windows object, where i have to specify the title of the window "AKAM Application". The problem is that i need JavaWindow's parent class some how so that i could get it children and specify the Class Name to be javaWindow and get my desired object, but either QTP does not catch it parent, or there isnt any at all, later is possible case. Is there any way that i can get objects of all opened windows and the specify javaWindow and get my desired window? I have tried following code but it does not work, probably because my application's window does not show "JavaWindow" in its title bar, i'm not sure
Dim WinDesc
Set WinDesc = Description.Create
WinDesc("nativeclass").Value = "JavaWindow"
Set WinChildren =Desktop.ChildObjects(WinDesc)
msgbox WinChildren.count
For i = 0 to WinChildren.Count - 1
winText = WinChildren(i).GetROProperty("label")
msgbox winText
Next
Kindly help!
Through descriptive programming, you can catch your JavaWindow on its index property:
Set myJavaWindow = JavaWindow("index:=0")
The 0 can be parameterised of course.
Edit after comment: To make your second example work:
Dim myJW, i
For i = 0 to 1023
Set myJW = JavaWindow("index:=" & i)
If not myJW.Exist Then Exit For
msgbox "Text for JavaWindow " & i & ": " & myJW.GetRoProperty("label")
Next
To match on a JavaWindow with a certain label, you can also use Descriptive Programming like:
myLabel = "Xyzzy!"
If JavaWindow("label:=" & myLabel, "index:=0").exist Then
msgbox "Woei! A Javawindow with label '" & myLabel & "' exists!"
End if

Selenium2's Select object not firing onchange event in IE8

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

Categories

Resources