Choosing random WebElement from drop down using Selenium with Java - java

I'm automating our application using Selenium 2.0 and Java. I would like to get a clearer understanding how can I overcome the problem with generating random ID for my WebElement and then click on it.
I have a list of elements in my drop down that all differs only in endings:
driver.findElement(By.id(""uxMiniFinderVoyageSelect_chzn_o_1")
driver.findElement(By.id(""uxMiniFinderVoyageSelect_chzn_o_2")
driver.findElement(By.id(""uxMiniFinderVoyageSelect_chzn_o_3")
driver.findElement(By.id(""uxMiniFinderVoyageSelect_chzn_o_4")
and so on till 250.
What I did is I called Random class where I declared a random variable within the range 1 to 250
Random random = new Random();
int x = random.nextInt(250) + 1;
Now I'm searching for my element this way
private WebElement cruiseSailing = driver.findElement(By.id("uxMiniFinderVoyageSelect_chzn_o_" + x));
That's all OK and is working as expected. The problem I'm facing is sometimes error message appears after selecting some of those elements from drop down. According to my test case, I need to catch this error, capture the screenshot and choose another element from the drop down. But once I set up cruiseSailing element, it chooses the same element over and over.Please see code example below:
private WebElement cruiseSailingDropDown = driver.findElement(By.id(Some ID));
private WebElement errorMessage = driver.findElement(By.xpath("some xpath expression"));
private WebElement cruiseSailing = driver.findElement(By.id("uxMiniFinderVoyageSelect_chzn_o_" + x));
cruiseSailingDropDown.click();
cruiseSailing.click();
Thread.sleep(2000);
if(errorMessage .isDisplayed){
System.out.printLn("Error message is displayed")
cruiseSailingDropDown.click();
cruiseSailing.click();
}else{
proceed further to the next step
Please advise how can I generate another ID for my cruiseSailing webelement.

The reason why it is choosing the same element again in case of failure is you are not reassigning the cruiseSailing value to new one .
There are 2 ways which i can think of :
Assign a new value to cruiseSailing inside the "If" block. You can do something as below inside "If" block.
cruiseSailing = driver.findElement(By.id("uxMiniFinderVoyageSelect_chzn_o_" + x));
Call the Orignial method again which sets cruiseSailing value to new value.
Note: You might want to remove below lines from If block if you are going on with 2nd approach.
cruiseSailingDropDown.click();
cruiseSailing.click();
For Taking screenshot you can create a method and call it inside If block.
Code for taking screenshot
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
// Now you can do whatever you need to do with it, for example copy somewhere
FileUtils.copyFile(scrFile, new File("c:\\error\\screenshot.png"));
Please vote up if this helped you. Thanks :)

Related

WebElement getText() doesn't work on Winium-Desktop

I'm trying to execute getText() on a WebElement instance but for some reason it doesn't work: pcresultsList.get(0).getText()
Maybe Winium doesn't support this method?
My code is:
public void monitorBasic() throws InterruptedException {
monitorFrame = driver.findElement(By.name("BEAM Monitor"));
WebElement resultsFrame = monitorFrame.findElement(By.id("ReportListBox"));
List<WebElement> pcresultsList = resultsFrame.findElements(By.className("TextBlock"));
System.out.println(pcresultsList.get(0).getText());
}
sorry for not posting the error I'm getting - the site tells me that my code is not indent and when i'm trying to present it as code the site tells i have too much code. :)
Have you tried using:
System.out.println(pcresultsList.get(0).getAttribute("Value"));
Also try to get other properties of the element to confirm you can get info.
The code below works for me:
element = Window.findElement(By.xpath("//*[contains(#ControlType,'ControlType.DataItem') and contains(#Name,'G15')]"));
System.out.println("Cell text: " + element.getText()); //writes Shipments
Let us know if this helps.
As far as I understand you are trying to get some text from an element which is inside a frame. In that case you need to switch to the frame first then acquire the text of any of the element within the frame.
You need to do:
Apply ImplicitlyWait for 2/3 seconds.
driver.switchTo().frame("BEAM Monitor"); // assuming that's the frame name.
Then click on a element inside the frame :
driver.findElement(By.id("ReportListBox")).click();
Create a list to get all the elements in a list:
List<WebElement> pcresultsList = driver.findElements(By.className("TextBlock"));
Create a for loop to iterate through the elements to get the text:
for(WebElement pcresult : pcresultsList)
{
System.out.println(pcresult.getText());
}
Let me know if this helps you.
I've found that with Winium, you need to get the Name attribute because getText() does not work correctly.

Appium : Verify relative element presence

Can you give a suggestion(please see pic) how can I check if selectIndicator is present on one block then I should choose another one. I know how to check if that element isPresent on whole page, but I need to find if it present on particular element. In my example I have Living Room chosen, and I need to check if DVR not chosen -choose that one. Any idea how can I do it? I was trying to check this way, but no luck:
WebElement element= driver.findElementByAccessibilityId("First element").findElementByAccessibilityId("Second element");
[http://i.stack.imgur.com/F98DM.png]
If I am not getting you wrong you want to implement a self defined data structure for an appropriate solution. That could be something similar to this :
public class DVRList {
//declare components required to comprise one item
private String dvrOptionText ;
private boolean dvrOptionCheck ;
// implement setter..getter for these two
}
...in some method set the value using the logic
DVRList dvrlist = new DVRList();
WebElement parentOfBoth = driver.findElement(By.xpath("
//android.widget.RelativeLayout[1]/android.widget.R‌​elativeLayout[1]");
String text = parentOfBoth.findElementByAccessibilityId("First element").getText();
dvrlist.setdvrOptionText(text);
if(isElement(parenOfBoth.findElementByAccessibilityId("Second element"))
dvrlist.setdvrOptionCheck(true);
else dvrlist.setdvrOptionCheck(false);
and thereafter you can use these parameters accordingly.
Note : Parameters and approach are generalised and should be modified for serving the exact purpose.

Selenium (java) can't get text from nested element without printing it

I try to get text from title of modal pop-up window. On the page there are many such windows - each with uniqe id. In each such modal window all elements have the same class names so first I need to point to the correct window and then look for particular element.
So I do it with this code:
public String getRFRTitle(String rfrNumber) {
return driver.findElement(By.id("rfr-details-dialog-"+rfrNumber)).
findElement(By.className("modal-title")).getText();
}
But it's not displaying for me anything.
What I have found is that when I print this title text before, this function works correctly.
I added this before returning value from the function:
System.out.println("tite: "+ driver.findElement(By.id("rfr-details-dialog-"+rfrNumber)).
findElement(By.className("modal-title")).getText());
I tried with initialisation of variables before returning text but without luck.
I can go with my workaround but I'm curious is this Java or Selenium issue.
This will most likely be a timeout issue. The following might work for you and if it doesn't, the stacktrace will give you more feedback.
By locator = By.cssSelector("#rfr-details-dialog-" + rfrNumber + " .modal-title");
int timeoutInSeconds = 10;
WebElement foundElement = new WebDriverWait(webdriver, timeoutInSeconds).until(ExpectedConditions.visibilityOfElementLocated(locator));
System.out.println("tite: " + foundElement.getText());

Java WebDriver Copy text Issue

Good Afternoon,
So I am trying to Copy some text from a field so I can paste it somewhere else in my test.
public static void validateTestCaseCreated(){
driver.findElement(By.xpath("//*[#id='mainForm:testTitle']")).click();
Action builder;
Actions copy = new Actions(driver);
copy.sendKeys(Keys.CONTROL + "a");
copy.sendKeys(Keys.CONTROL + "c");
builder = copy.build();
builder.perform();
The problem when it reaches line 6 it only sends c, it ignores the CONTROL. So my end result is not copying the text but highlighting the text then entering c.
You could just copy the value from the text field into a variable and store it for use later.
Pull it from the page using your code along with the get attribute method.
String valueInField = driver.findElement(By.xpath("//*[#id='mainForm:testTitle']")).getAttribute("value");
That will grab the text from the field and put it into the variable for later use.
I'm not sure if this is doing fully what you are trying to do, seeing as you are trying to do a crtl+c, but this method is how to grab text using webdriver.
If your field is an input element, maybe you can do something like this instead:
driver.findElement(By.xpath("//*[#id='mainForm:testTitle']")).click().get_attribute("value");

Selenium WebDriver: I want to overwrite value in field instead of appending to it with sendKeys using Java

In WebDriver, if I use sendKeys it will append my string to the value that already exists in the field. I can't clear it by using clear() method because the second I do that, the webpage will throw an error saying that it has to be between 10 and 100. So I can't clear it or an error will be thrown before I can put in the new value using sendKeys, and if I sendKeys it just appends it to the value already there.
Is there anything in WebDriver that lets you overwrite the value in the field?
You can also clear the field before sending it keys.
element.clear()
element.sendKeys("Some text here")
I think you can try to firstly select all the text in the field and then send the new sequence:
from selenium.webdriver.common.keys import Keys
element.sendKeys(Keys.chord(Keys.CONTROL, "a"), "55");
Okay, it is a few days ago...
In my current case, the answer from ZloiAdun does not work for me, but brings me very close to my solution...
Instead of:
element.sendKeys(Keys.chord(Keys.CONTROL, "a"), "55");
the following code makes me happy:
element.sendKeys(Keys.HOME, Keys.chord(Keys.SHIFT, Keys.END), "55");
So I hope that helps somebody!
In case it helps anyone, the C# equivalent of ZloiAdun's answer is:
element.SendKeys(Keys.Control + "a");
element.SendKeys("55");
This worked for me.
mElement.sendKeys(Keys.HOME,Keys.chord(Keys.SHIFT,Keys.END),MY_VALUE);
Use this one, it is trusted solution and works well for all browsers:
protected void clearInput(WebElement webElement) {
// isIE() - just checks is it IE or not - use your own implementation
if (isIE() && "file".equals(webElement.getAttribute("type"))) {
// workaround
// if IE and input's type is file - do not try to clear it.
// If you send:
// - empty string - it will find file by empty path
// - backspace char - it will process like a non-visible char
// In both cases it will throw a bug.
//
// Just replace it with new value when it is need to.
} else {
// if you have no StringUtils in project, check value still empty yet
while (!StringUtils.isEmpty(webElement.getAttribute("value"))) {
// "\u0008" - is backspace char
webElement.sendKeys("\u0008");
}
}
}
If input has type="file" - do not clear it for IE. It will try to find file by empty path and will throw a bug.
More details you could find on my blog
Had issues using most of the mentioned methods since textfield had not accepted keyboard input, and the mouse solution seem not complete.
This worked for to simulate a click in the field, selecting the content and replacing it with new.
Actions actionList = new Actions(driver);
actionList.clickAndHold(WebElement).sendKeys(newTextFieldString).
release().build().perform();
Use the following:
driver.findElement(By.id("id")).sendKeys(Keys.chord(Keys.CONTROL, "a", Keys.DELETE), "Your Value");
This is something easy to do and it worked for me:
//Create a Javascript executor
JavascriptExecutor jst= (JavascriptExecutor) driver;
jst.executeScript("arguments[1].value = arguments[0]; ", 55, driver.findElement(By.id("id")));
55 = value assigned
The original question says clear() cannot be used. This does not apply to that situation. I'm adding my working example here as this SO post was one of the first Google results for clearing an input before entering a value.
For input where here is no additional restriction I'm including a browser agnostic method for Selenium using NodeJS. This snippet is part of a common library I import with var test = require( 'common' ); in my test scripts. It is for a standard node module.exports definition.
when_id_exists_type : function( id, value ) {
driver.wait( webdriver.until.elementLocated( webdriver.By.id( id ) ) , 3000 )
.then( function() {
var el = driver.findElement( webdriver.By.id( id ) );
el.click();
el.clear();
el.sendKeys( value );
});
},
Find the element, click it, clear it, then send the keys.
This page has a complete code sample and article that may help.
This solved my problem when I had to deal with HTML page with embedded JavaScript
WebElement empSalary = driver.findElement(By.xpath(PayComponentAmount));
Actions mouse2 = new Actions(driver);
mouse2.clickAndHold(empSalary).sendKeys(Keys.chord(Keys.CONTROL, "a"), "1234").build().perform();
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].onchange()", empSalary);
WebElement p= driver.findElement(By.id("your id name"));
p.sendKeys(Keys.chord(Keys.CONTROL, "a"), "55");

Categories

Resources