Selenium, how to Copy a few words that are always different? - java

Im trying to copy automatically a Name out of the webbrowser but the Name changes so I don't know how to copy it.
I've tried to doublecklick it or to "ctrl + c" it but it didn't work.
WebDriver driver = new ChromeDriver();
driver.get("https://realnamecreator.alexjonas.de/?l=de#");
driver.findElement(By.linkText("[+] Filter-Optionen")).click();
driver.findElement(By.id("gender")).click();
new Select(driver.findElement(By.id("gender"))).selectByVisibleText("w");
driver.findElement(By.id("gender")).click();
driver.findElement(By.id("button")).click();
and after this I want to copy the name into my Program. So I would say
String text = driver...

First you need to retrieve the element, then call the getText method documented here:
driver.findElement(By.id("realname")).getText()
Hope that helps.

You should not use thread-sleep... use WebDriverWait:
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("realname")));
Then use getText():
String text = driver.findElement(By.id("realname")).getText()
Hope this helps!

The link you have shared has the element with realname id before it generates and shows the name.
So waiting for visibility of the element with id realname would not give you the expected result.
You have to wait for the invisibility of the image that shows on the page load but doesn't show when the name is shown.
Try this,
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.invisibilityOfElementLocated(By.cssSelector("#realname > a")));
String text = driver.findElement(By.id("realname")).getText();

Related

Find element using explicit wait within another element

I have the following code:
List<MobileElement> messages = driver.findElements (By.id ("body_bubble")); //find all messages
MobileElement lastMessage = messages.get (messages.size () - 1); //get last message
// xpath query to check if the message is delivered
String xpathDeliveryStatus = ".//*[contains(#resource-id, 'delivered_indicator') or contains(#resource-id, 'read_indicator') or contains(#resource-id, 'sent_indicator')]";
MobileElement deliveryStatus = lastMessage.findElement (By.xpath (xpathDeliveryStatus));
I want to do the same except that I want to find the deliveryStatus variable using explicit wait.
So I want to find the deliveryStatus variable inside the lastMessage variable using wait.until (ExpectedConditions.visibilityOfElementLocated (By.locator))
How can I do this?
I don't want to do it using one immense Xpath. Besides, I don't even know how to find the last element with the id body_bubble using Xpath, as the number of these elements is not fixed and always changing.
P.S. For example, in Python we can define WebDriverWait with an element in the constructor instead of driver:
WebDriverWait(webelement, self.timeout)
Unfortunately, it does not work in Java.
Based on the Java documentation on ExpectedConditions, it looks like we can use presenceOfNestedElementLocatedBy to add explicit wait on the child element:
WebDriverWait wait = new WebDriverWait(driver, 15);
WebElement childElem = wait.until(
ExpectedConditions.presenceOfNestedElementLocatedBy(lastMessage, By.xpath(xpathDeliveryStatus)));

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.

Choosing random WebElement from drop down using Selenium with 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 :)

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

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