How to select element in pop up message using webdriver? - java

i have a web page where i can create a document.
When i save the document i have a message like "Document successfully saved"
The message appears only for 3 seconds.
How can i find the element with webdriver to check the message has been displayed during my test.
In the html code, i tried to catch the code for this message, it appears for 3 seconds and the disappaeared.
The code is here:
<div class="alert alert-success top center alert-notify alert-icon>
Document successfully saved.
<span class="Close"></span>
I tried this without success:
try {
Alert alert = driver.switchTo().alert();
message = alert.getText();
alert.accept();
} catch (Exception e) {
message = null;
}
System.out.println("message"+message);
return message;
}
then i tried this without success too:
driver.findElement(By.className("alert alert-success top center alert-notify")).isDisplayed();
Thread.sleep(3000);
System.out.println(" Alert message is displayed");
Can anyone help me please, i don't know how to handle with

your second try is the right way to detect the message, but your have to try for 3 seconds to find the element.
It should look like this
while (!elementFound || stillWithin3Seconds){
elementFound = findAlertByClassName()
}
assetTrue(elementFound)
You have to look all the time. In your code you are sleeping. When the dialog appears in this time, you won't notice it.

Related

unable to capture 'g-recaptcha-response' for Recaptchav2 with Selenium

So I've been trying to build a webscraper but some of the data I need to scrape is locked behind a reCaptcha. From what I've gathered scouring around on the internet is every captcha has a TextArea element with the 'g-recaptcha-response' that gets filled in as the captcha is completed. The current solution for testing is to simply get around the captcha with me manually doing it and trying to capture the response and feed it back into the headless browser however I'm unable to get the response since as soon as the answer is submitted it can no longer find the response element.
org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"css selector","selector":"*[name='g-recaptcha-response']"}
public static String captchaSolver(String captchaUrl) {
setUp();
driver.get(captchaUrl);
new WebDriverWait(driver,2);
try {
while (true) {
String response = driver.findElement(By.name("g-recaptcha-response")).getText();
if (response.length()!=0) {
System.out.println(response);
break;
}
}
}catch (Exception e){
e.printStackTrace();
}
return "";
}
Try to find the element by CSS like this:
*[name*='g-recaptcha-response']

Selenium message-error and message-success in java

I'm facing a problem with finding an element that does not exist. When I try to login into the application, if it failed login it will show the element -
dr.findElement(By.className("message-error ")).getText();
And after a successful login it will show this:
dr.findElement(By.className("message-success")).getText();
When I run the code and it doesn't find the element, then execution stops with the exception: element is not found
String mes=null;
mes=dr.findElement(By.className("message-success")).getText();
if(mes!=null) {
File out= new File("success.txt");
FileWriter fr =new FileWriter(out,true);
PrintWriter pw=new PrintWriter(fr);
pw.println(mes+"|"+user.get(i)+"|"+pass.get(i));
pw.close();
}
mes=dr.findElement(By.className("message-error")).getText();
if(mes!=null) {
File out= new File("error.txt");
FileWriter fr =new FileWriter(out,true);
PrintWriter pw=new PrintWriter(fr);
pw.println(mes+"|"+user.get(i)+"|"+pass.get(i));
pw.close();
}
The element does not appear.
For example, the success element will not shown until it is successful and the error element will not appear in the CSS until it gets an error.
So how can I tell it if element should exit or come to live or appear do an action?
What is the right thing to do in an if statement if the login is successful? Do this and login fail do this?
Use WebdriverWait to wait for the visibility of success message,
// After valid login
WebDriverWait wait = new WebDriverWait(driver, 60);
WebElement successmessage wait.until(ExpectedConditions.visibilityOfElementLocated(By.className("message-success")));
sucessmessage.getText();
Similarly for error message,
// After invalid login
WebElement errormessage wait.until(ExpectedConditions.visibilityOfElementLocated(By.className("message-error")));
errormessage.getText();
What i think is you have same element but the class getting change as per application behavior. suppose if you are able to login in the application then it show the message element with class having attribute message-success and if it won't allow then error message with class having attribute 'message-error' in the same element.
I've handled the same in below code -
// first get the message element with some other locator or other attribute (don't use class name)
WebElement message = driver.findElement(By.locator);
if(message.getAttribute("class").contains("message-success")){
System.out.println("Success message is " + message.getText())
// write the code to perform further action you want on login success
}else if (message.getAttribute("class").contains("message-error")){
System.out.println("Error message is " + message.getText())
// write the code to perform further action you want on login Fail
}else{
System.out.println("Message is empty" + message.getText())
}
Let me know if you have further queries.
My Choice is to use Webdriver wait. it is the perfect way to find an element.
public WebDriverWait(WebDriver driver,15)
WebElement successmessage = wait.until(ExpectedConditions.visibilityOfallElementLocatedby(By.className("message-success")));
sucessmessage.getText();
visibilityOfallElementLocatedby :
An expectation for checking that all elements present on the web page that match the locator are visible. Visibility means that the elements are not only displayed but also have a height and width that is greater than 0.
The above i wrote is for success Message, similar way try for invalid login.
To use different types of wait, check this doc - https://seleniumhq.github.io/selenium/docs/api/java/allclasses-noframe.html
search Wait in that document.
this is the answer for the question it work with me
try {
WebElement sucmes=dr.findElement(By.xpath("//div[#class='message']"));
String suclogin="login success:";
if(sucmes.getText().contains(suclogin)) {
File suclogin= new File("suclog.txt");
FileWriter suclogr =new FileWriter(suclogin,true);
PrintWriter suclogrw=new PrintWriter(suclogr);
suclogrw.println(sucmes.getText());
suclogrw.close();
}else{
//the other action here
}
}

Continue Selenium Test instead of Timeout in WebDriverWait

i am using WebDriverWait in Selenium, i want to wait 10 second to wait if some Alert or Confirm box will appear, if it appears i will accept it. for example if confirm box ask me to "Leave Page" or "Stay on Page" then i want to leave page automatically, and if alert is not appeared in 10 seconds then continue code Excecution instead of throwing Exception. or you can tell me some way to accept All confirm, alert boxes automatically during whole selenium test. thanks
here is my code
WebDriver driver = new FirefoxDriver();
driver.get("https:www.google.com");
WebDriverWait wait = new WebDriverWait(driver, 10 );
if(wait.until(ExpectedConditions.alertIsPresent())==null)
{
System.out.println("alert was not present");}
else{
Alert alert = driver.switchTo().alert();
alert.accept();
System.out.println("alert was present");}
try/catch is useful to catch/handle the exception. Just place alert code in try block, if any exception occurs, it will handle in catch block and there after execution will continue..
WebDriver driver = new FirefoxDriver();
driver.get("https:www.google.com");
WebDriverWait wait = new WebDriverWait(driver, 5 );
try{
if(wait.until(ExpectedConditions.alertIsPresent())==null)
{
System.out.println("alert was not present");
}else{
Alert alert = driver.switchTo().alert();
alert.accept();
System.out.println("alert was present");
}
}catch(Exception e){
System.out.println("ignored alret not present exception" +e.getMessage());
}
}
Thanks

java/selenium - how can I click on an element from a form that pops up on top of the main page?

At a certain point in my automation project, I have to click on an element that is part of a form that pops up on top of the main page (it doesn't go away like those menus that show up when hovering over a certain element and then disappear) after successfully accessing the page and clicking on the element that brings out the form.
I've been trying all kinds of solutions suggested in comments from other questions, such as using offsets and waiting until the element became clickable, but none worked for me.
Here's the code in its current state for the first field, "Name":
try {
System.out.println("Filling in mandatory fields of the contact form... ");
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[#id='jcemediabox-popup-frame']")));
System.out.println("Filling in name... ");
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("(//div[#class='formBody']/input)[1]")));
WebElement nameField = driver.findElement(By.xpath("(//div[#class='formBody']/input)[1]"));
actions.moveToElement(nameField).build().perform();
actions.moveByOffset(5, 5).build().perform();
nameField.sendKeys(contactInput[1]);
nameField.submit();
System.out.println("Filled in name");
} catch (Exception e) {
System.out.println("Could not complete actions on: contact form");
e.printStackTrace();
}
Edit - working code (thanks segalaj):
try {
System.out.println("Filling in mandatory fields of the contact form... ");
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//iframe[#id='jcemediabox-popup-iframe']")));
driver.switchTo().frame(driver.findElement(By.xpath("//iframe[#id='jcemediabox-popup-iframe']")));
driver.wait(pauseInSeconds);
System.out.println("Filling in name... ");
wait.until(ExpectedConditions.elementToBeClickable(By.name("form[Name]")));
driver.findElement(By.name("form[Name]")).sendKeys(contactInput[0]);
System.out.println("Filled in name");
driver.wait(shorterWait);
driver.switchTo().defaultContent();
} catch (Exception e) {
System.out.println("Could not complete actions on: contact form");
e.printStackTrace();
}
As your popup is in an iframe, you need to tell to you webdriver to switch to the iframe:
<webdriver>.switchTo().frame(<iframe-webelement>);
Then you'll be able to access to iframe elements.
Do not forget to come back to the main page when you're done with the frame.
You can find the doc here.
Hope that helps.

Selenium automatically accepting alerts

Does anyone know how to disable this? Or how to get the text from alerts that have been automatically accepted?
This code needs to work,
driver.findElement(By.xpath("//button[text() = \"Edit\"]")).click();//causes page to alert() something
Alert alert = driver.switchTo().alert();
alert.accept();
return alert.getText();
but instead gives this error
No alert is present (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 2.14 seconds
I am using FF 20 with Selenium 2.32
Just the other day i've answered something similar to this so it's still fresh. The reason your code is failing is if the alert is not shown by the time the code is processed it will mostly fail.
Thankfully, the guys from Selenium WebDriver have a wait already implemented for it. For your code is as simple as doing this:
String alertText = "";
WebDriverWait wait = new WebDriverWait(driver, 5);
// This will wait for a maximum of 5 seconds, everytime wait is used
driver.findElement(By.xpath("//button[text() = \"Edit\"]")).click();//causes page to alert() something
wait.until(ExpectedConditions.alertIsPresent());
// Before you try to switch to the so given alert, he needs to be present.
Alert alert = driver.switchTo().alert();
alertText = alert.getText();
alert.accept();
return alertText;
You can find all the API from ExpectedConditions here, and if you want the code behind this method here.
This code also solves the problem because you can't return alert.getText() after closing the alert, so i store in a variable for you.
Before you accept() the alert you need to get the text. What you're doing right now is accepting (clicking "OK") on the alert then trying to get the alerts text after it's out of the screen, i.e. no alert present.
Try the following, I just added a String that retrieves the alert text then return that string instead.
driver.findElement(By.xpath("//button[text() = \"Edit\"]")).click();//causes page to
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
alert.accept();
return alertText;
Selenium webdriver does not wait for the alert.
So it will try to switch to a non-existent alert and thats why it fails.
For a quick and not so good fix, put in a sleep.
A better solution would be to implement your own wait for alert method, before trying to switch to the alert.
UPDATE
Something like this, copy pasted from here
waitForAlert(WebDriver driver)
{
int i=0;
while(i++<5)
{
try
{
Alert alert3 = driver.switchTo().alert();
break;
}
catch(NoAlertPresentException e)
{
Thread.sleep(1000)
continue;
}
}
}
Following method with synchronized option will add more stability
protected Alert getAlert(long wait) throws InterruptedException
{
WebDriverWait waitTime = new WebDriverWait(driver, wait);
try
{
synchronized(waitTime)
{
Alert alert = driver.switchTo().alert();
// if present consume the alert
alert.accept();
return alert;
}
}
catch (NoAlertPresentException ex)
{
// Alert not present
return null;
}
}
Here is the JavaScript answer. The documentation has examples for all languages. https://www.selenium.dev/documentation/en/webdriver/js_alerts_prompts_and_confirmations/
await driver.wait(until.alertIsPresent());
el = driver.switchTo().alert();
await el.accept();

Categories

Resources