How to handle error message in Selenium - selenium

I'm automating an application using Selenium so what is happening is when the script runs and it hits the login button an error comes up in the top right which stops further execution. What I want is need a way by which i can capture this "error message" so that I would know the cause of the halt of the application execution.I'm attaching the image of error and also the code that I have tried but it didnt work.
#FindBy(xpath="//*[#id='toast-container']/div/div]")
static WebElement errorMessage;
WebDriverWait wait = new WebDriverWait(CommonBrowserSetup.driver, 15);
wait.until(ExpectedConditions.visibilityOf(errorMessage));
String mess=errorMessage.getText();
System.out.println(mess);

If you want to capture Unknown error occured
Just try the following code and let me know if it works for you.
After the login button is clicked add the following:
WebElement Error = driver.findElement(By.xpath("//div[contains(text(),'Unknown error occured')]"));
if(Error.isDisplayed()){
String Errormessage = Error.getText();
System.out.println(Errormessage);
}

Related

How to handle a "Wait" or "loading for a web application

I am learning selenium by writing automation code for one web application.
When a page get loaded , I am calling Thread.sleep() method and then setting an element ID.
In below code , first clicking submit button and then waiting for "Success" div loader.
isElementPresent("btn_settingsSubmit_id").click();
Thread.sleep(2000);
WebDriverWait waitSet = new WebDriverWait(driver,40);
waitSet.until(ExpectedConditions.visibilityOf(driver.findElement(By.xpath("//span[#class='jq-toast-loader jq-toast-loaded']"))));
//*********************************Add Priority***************************************
Thread.sleep(6000);
WebElement PT=isElementPresent("lnk_priorityTab_id");
PT.click();
WebDriverWait wait02 = new WebDriverWait(driver,30);
wait02.until(ExpectedConditions.invisibilityOfElementLocated(By.className("preloader")));
Here issue is if internet is slow or server takes time to send response  then sleep is not helpful and getting an error like element id not found.
which is the way to handle this page/ element loading?

PayPal Sandbox not able to find password field

I'm currently using HtmlUnitDriver, and while I am able to set the username, I keep getting an error that Selenium could not find the password field. I am using JavascriptExecutor to set these values inside the PayPal sandbox form, but I'm still unable to get past the password step.
HtmlUnitDriver driver = new HtmlUnitDriver(BrowserVersion.CHROME)
JavascriptExecutor executor = (JavascriptExecutor)driver
driver.setJavascriptEnabled(true)
driver.get(url)
log.debug "setting username"
Thread.sleep(5000)
if(driver.findElement(By.xpath("//*[#id='email']")).displayed){
executor.executeScript("document.getElementById('email').value = 'email';")
log.debug "Username was set"
} else {
log.debug "We never set the username!"
}
if(driver.findElement(By.xpath("//*[#id='password']")).displayed){
executor.executeScript("document.getElementById('password').value='password';")
} else {
log.debug "We never set the password."
}
I understand that I am setting sleeps in there, and that's bad practice for Selenium testing, but I'm pretty much at my wits end here. The url in that case is the link to express checkout, which is something like this: https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=#################
Any help would be greatly appreciated!
As I mentioned earlier, there are multiple issues here:
When I load the initial page, I see this UI:
As you see, Password button is really invisible. So unless we click the Next button, there's no chance that this script will work.
So the following has to be added in order to achieve any kind of progress:
driver.findElement(By.id("btnNext")).submit()
However unfortunately I cannot get this button to be clicked correctly with HtmlUnitDriver. It seems button is clicked, but nothing happens, so Password field remains hidden. However as soon as I switch to ChromeDriver, this is not an issue anymore, and the same code works. So I guess you've hit one of the HtmlUnitDriver limitations, and need to use Chrome or Gecko driver.
Finally a few adjustments to the code will make it more reliable and faster. Here's the final version that works for "real" browsers (Chrome or Gecko):
WebDriver driver = new ChromeDriver()
WebDriverWait wait = new WebDriverWait(driver, 10)
driver.get(url)
// The following line waits for email field to appear. It's more economical and reliable than Thread.sleep
WebElement email = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("email")))
log.debug "setting username"
email.sendKeys("email#gmail.com")
log.debug "Username was set " + email.getAttribute("value")
driver.findElement(By.id("btnNext")).submit()
// Here again using the same method to verify when password becomes visible
WebElement password = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("password")))
log.debug "setting password"
password.sendKeys("password")
log.debug "Password was set " + password.getAttribute("value")
(note: I wrote this code in Java, so I hope I translated all correctly, but if I didn't feel free to fix it)
The result of this script looks like this in Chrome:
With HtmlUnitDriver, script will show an error:
org.openqa.selenium.TimeoutException: Expected condition failed: waiting for visibility of element located by By.id: email (tried for 10 second(s) with 500 MILLISECONDS interval)

Cant insert text - a msg that the element is not visible is displayed

I run automation on a site that after I click on a button and a screen of PayPal is opened for inserting details. The PayPal is opened in another tab. I added a syntax that move the testing to the relevant tab and then I insert a syntax that checks that the "email input" field exists (to check that it is really goes to the correct tab) - and the result of this test :- field exists.
Then - I add a syntax for the same field to insert the email and the test is failed - the text is not inserted and there is a msg that the field is not visible.
No need to do scroll because the filed is in the top of the screen.
What can I do in this case?
This is the relevant code:
String oldTab = driver.getWindowHandle();
comOps.clickOrChose(PLS.buyButton);
Thread.sleep(4000);
ArrayList<String> newTab = new ArrayList<String> (driver.getWindowHandles());
newTab.remove(oldTab);
driver.switchTo().window(newTab.get(0));
comOps.verifyElementExist(PLP.payPalEmail);
comOps.insertText(PLP.payPalEmail, "paypal-buyer#makeitleo.com");
The reason you get this error message is that the element apparently exists but is not visible when you try to enter text to it. There are a lot of possible reasons why the element is not visible.
Given that a new tab is opended a probable reason is that the page (and its elements) is still loading. If this is the case, you need to wait for the visiblity of the element, e.g. using this piece of code (before inserting text):
WebDriverWait wait = new WebDriverWait(driver, 300); //waiting up to 5 minutes
ExpectedCondition<WebElement> condition =
ExpectedConditions.visibilityOf(PLP.payPalEmail);
wait.until(condition);
Note: that this solution assumes that PLP.payPalEmail is of type org.openqa.selenium.WebElement. If it is of type org.openqa.selenium.By use visibilityOfElementLocated(By locator).
Telling from your code snippet, I assume that comOps is an object of a class wrapping all Selenium actions. So, it is a good idea to place the above code in some method inside that class which could look like this:
public void verifyElementVisible(WebElement element) {
WebDriverWait wait = new WebDriverWait(driver, 300); //ToDo: use configurable timeout
ExpectedCondition<WebElement> condition =
ExpectedConditions.visibilityOf(element);
wait.until(condition);
}
and call it like this
comOps.verifyElementVisible(PLP.payPalEmail);

phantomjs with webdriver: Can't handle popup/alert

I am trying to handle popup using phantomjs as a driver and I want to copy the text of alert/popup in variable.
I write the code:
But I am getting exception:Exception in thread "main" java.lang.NullPointerException
Anyone knows how to handle popup/alert using phantomjs with webdriver.
I write the code:
js.executeScript("window.alert = function(msg){JavascriptExecutor js=(JavascriptExecutor) driver;
document.lastAlert=msg;};");
Object text = js.executeScript("return document.lastAlert");
System.out.println(text.toString());
Selenium has methods to interact with javascript alerts. You can interact with a javascript alert as follows:
Alert alert = driver.switchTo().alert();
From here on you can get the alert text with:
String alertText = alert.getText();
You do not need any javascript to do this. Just plain Java code does all that for you.

Selenium Webdriver - how to close the first pop up window and go to the actual page

I'm trying to automate the webpage "http://www.quikr.com",when I open this you will get a pop up window first saying "Please Choose Your Location" then after closing it , I can see the main page of quikr.
I tried closing that Popup page by automation ,but not able to do
Tried using xpath
driver.findElement(By.xpath("//*[#id='csclose']/strong")).click();
Tried using className
driver.findElement(By.className("cs-close cs-close-v2")).click();
Tried using id
driver.findElement(By.id("csclose")).click();
Please help me with this
to close multiple popups in webdriver and switch to parent window
String parent = driver.getWindowHandle();
Set<String> pops=driver.getWindowHandles();
{
Iterator<String> it =pops.iterator();
while (it.hasNext()) {
String popupHandle=it.next().toString();
if(!popupHandle.contains(parent))
{
driver.switchTo().window(popupHandle);
System.out.println("Popu Up Title: "+ driver.switchTo().window(popupHandle).getTitle());
driver.close();
The Following Code Works for Me to Handle Pop Up/ Alerts in Selenium Webdriver
Just Copy Paste this Code After the Event which is triggering the Pop up/Alert i.e after clicking on save.
if(driver.switchTo().alert() != null)
{
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
alert.dismiss(); // alert.accept();
}
in your case you try to run this code at starting of the code bcz it will directly close the pop up
Since this is a JavaScript modal, when the page finishes loading the JavaScript code could still be running. The solution is to wait until the button to close the modal be displayed, close it and then follow with your test. Like this:
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(30));
wait.Until(ExpectedConditions.ElementIsVisible(By.Id("csclose")));
driver.FindElement(By.Id("csclose")).Click();
Tested myself and works fine.
Hope it helps.
i have tried it in ruby and this one works
see if this can help you in any way :)
require 'selenium-webdriver'
require 'test/unit'
require 'rubygems'
class Tclogin < Test::Unit::TestCase #------------ define a class----------------
def setup
##driver = Selenium::WebDriver.for :firefox
##driver.navigate.to "http://www.quikr.com" #---- call url----
##wait = Selenium::WebDriver::Wait.new(:timeout => 60) # seconds #----define wait------
end
def test_login
##driver.find_element(:css, "strong").click
end
end
you can also use follwing xpath
##driver.find_element(:xpath, "//a[#id='csclose']/strong").click
public void closePopup() throws Exception {
WebDriver driver = new InternetExplorerDriver();
driver.get("http://www.quikr.com/");
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("csclose"))).click();
System.out.println("Successfully closed the start Popup");
}
Try driver.findElement(By.Id("csclose")).click(); I hope that will help
Simple pressing Alt + F4 buttons worked for me, e.g.:
driver.findElement(By.cssSelector("html body div div img")).sendKeys(Keys.chord(Keys.ALT, Keys.F4));