selenium webdriver detect UI pop up error messages - java

I have this react application being tested using selenium webdriver.
if my login is wrong, how do i detect the text using selenium webdriver? I am unable to find the code/ figure out how to trap the pop up message . 'authentication failed'
#Test
public void failed_login() {
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\rahul\\Downloads\\chromedriver_win32_83\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("http://testingapp.workspez.com");
driver.manage().window().maximize();
WebElement username = driver.findElement(By.id("field_email"));
WebElement password = driver.findElement(By.id("field_password"));
WebElement login = driver.findElement(By.xpath("//*[text()='Log In']"));
username.sendKeys("wrongemail#gmail.com");
password.sendKeys("wrongpassword");
login.click();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
driver.manage().timeouts().implicitlyWait(120, TimeUnit.SECONDS);
String url = driver.getCurrentUrl();
assertEquals(url, "http://testingapp.workspez.com/login");
}

You can use below code to verify if authentication failed pop up is displayed or not:
List<WebElement> popUpElement = driver.findElements(By.id("client-snackbar");
if(popUpElement.size() != 0){
System.out.println("Pop up is Present "+popUpElement.get(0).getText());
}else{
System.out.println("Pop up is Absent");
}

After you perform click, you can use Explicit Wait:
try{
WebDriverWait wait = new WebDriverWait(driver, 10); //10 seconds
WebElement messageElement = wait.until(
ExpectedConditions.visibilityOfElementLocated(
By.xpath("//*[#id = 'client-snackbar']")
)
);
//if reach here, means the error is visible.
System.out.println(messageElement.getText());
}catch(TimeoutException ignored){
//if trigger timeoutexception
//that means the element with message is not visible, that means no error
}
This will wait 10 seconds for the element to be visible.
If it is not visible, it will throws TimeoutException which you can simply ignore.
That means the error was not visible in first 10 seconds after click.
You can change the time with whatever you want.

You can find the locator for that toast message.
For locating web element
Go to your login.
Enter your invalid credentials.
Press F12 and go to console/Sources
Click on login to get your message.
Press F8 to pause it. Now you can inspect your element.
So from webelement you can fetch text with gettext() method.
You can apply explicit wait to wait for your error message.

Related

How to wait till text value is fully loaded in selenium

I tried the following code in Selenium to get the row values.
public static void main(String[] args) throws InterruptedException {
WebDriverManager.chromedriver().setup();
ChromeDriver driver = new ChromeDriver();
driver.get("https://www2.asx.com.au/");
driver.manage().window().maximize();
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
try {
WebElement cookies = driver.findElementByXPath("//button[text()='Accept All Cookies']");
wait.until(ExpectedConditions.elementToBeClickable(cookies)).click();
} catch (Exception e) {
System.out.println("cookies pop up not found");
}
WebElement el = driver
.findElementByXPath("//*[#class='markit-home-top-five aem-GridColumn aem-GridColumn--default--12']");
wait.until(ExpectedConditions.visibilityOf(el));
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", el);
List<WebElement> elements = driver.findElementsByXPath("//caption[text()='Gains']//ancestor::table//tr");
for (int i = 1; i <= elements.size(); i++) {
Thread.sleep(2000);
System.out.println(driver.findElementByXPath(
"//caption[text()='Gains']//ancestor::table//tr[" + i + "]//span[#class='value-with-arrow']")
.getText());
}
}
I faced two issues:
The 'Allow all cookies' button is not getting clicked and the pop up remains there. 'cookies pop up not found' is getting printed in the output.
The value of the tables are not getting printed without sleep. in the below output ,it is shown that the first text value is printed as -- as the value was still loading. How to provide till the value is fully loaded.
Thanks in advance!
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.textToBePresentInElementLocated(By.id("element_id"), "The Text"));
use webdriver wait , you can use expected condition texttobepresent or element to be present
https://www.selenium.dev/selenium/docs/api/java/org/openqa/selenium/support/ui/ExpectedConditions.html#textToBePresentInElementLocated(org.openqa.selenium.By,java.lang.String)

Unable to enter text in Compose new Tweet box on Twitter using Selenium Webdriver

I'm trying to automate Tweeting using Selenium Webdriver in Chrome. I can login and click the Tweet button, opening the Compose new Tweet box, but when I try to enter text with element.sendKeys(tweetMessage); I get
org.openqa.selenium.ElementNotInteractableException: element not
interactable
Using:
selenium-java-3.141.59
chrome=74.0.3729.169
(Driver info: chromedriver=74.0.3729.6)
Here's the relevant code:
String composeTweetXpath = "//div[#aria-labelledby='Tweetstorm-tweet-box-0-label Tweetstorm-tweet-box-0-text-label']//div";
String tweetMessage = "This is my test Tweet";
WebDriver driver;
driver = new ChromeDriver();
.
.
.
.
try {
element = wait.until(ExpectedConditions.elementToBeClickable(By.xpath(composeTweetXpath)));
System.out.println("After wait until...");
element = driver.findElement(By.xpath(composeTweetXpath));
System.out.println("After driver.findElement...");
element.click();
System.out.println("After element.click...");
element.sendKeys(tweetMessage);
System.out.println("Found Tweet box and typed message");
} catch ( Exception e1) {
System.out.println("Failed to find Tweet box");
e1.printStackTrace();
}
I'm surprised that I don't get the error on element.click(); but on element.sendKeys(tweetMessage); My output from this snippet is :
After wait until...
After driver.findElement...
After element.click...
Moved to element...
Failed to find Tweet box
org.openqa.selenium.ElementNotInteractableException: element not interactable
I've also tried using:
String js = "arguments[1].value = arguments[0]; ";
System.out.println("Executing : " + js);
javascript.executeScript(js, tweetMessage, element);
...instead of element.sendKeys(tweetMessage); This doesn't fall into the } catch ( Exception e1) { block, but still doesn't enter the text in the Compose new Tweet box.
Strangely enough, if I use driver = new FirefoxDriver(); I get the TimeoutException error at this line:
element = wait.until(ExpectedConditions.elementToBeClickable(By.xpath(composeTweetXpath)));
org.openqa.selenium.TimeoutException: Expected condition failed:
waiting for element to be clickable: By.xpath:
//div[#aria-labelledby='Tweetstorm-tweet-box-0-label
Tweetstorm-tweet-box-0-text-label']//div (tried for 10 second(s) with
500 milliseconds interval)
Use a CSS selector
ChromeDriver newDriver = new ChromeDriver();
WebDriverWait waits = new WebDriverWait(newDriver, 50);
newDriver.get("https://twitter.com/");
newDriver.findElement(By.name("session[username_or_email]")).sendKeys("arungnairktm#gmail.com");
newDriver.findElement(By.name("session[password]")).sendKeys("Cisco_12345678");
newDriver.findElement(By.className("submit")).click();
WebElement composes = waits
.until(ExpectedConditions.visibilityOfElementLocated(By.id("global-new-tweet-button")));
composes.click();
WebElement tweets = waits.until(ExpectedConditions.visibilityOf(newDriver.findElement(By.cssSelector(
"#Tweetstorm-tweet-box-0 > div.tweet-box-content > div.tweet-content > div.RichEditor.RichEditor--emojiPicker.is-fakeFocus > div.RichEditor-container.u-borderRadiusInherit > div.RichEditor-scrollContainer.u-borderRadiusInherit > div.tweet-box.rich-editor.is-showPlaceholder"))));
tweets.click();
tweets.sendKeys("heys");

Unable to locate an element using xpath error in selenium-java

This is the code I am trying to execute
public WebDriver createPart() {
try {
driver.findElement(By.id("username")).sendKeys("502409373");
driver.findElement(By.id("password")).sendKeys("Magic14Magic");
driver.findElement(By.id("submitFrmShared")).click();
driver.manage().timeouts().implicitlyWait(70, TimeUnit.SECONDS);
driver.manage().timeouts().pageLoadTimeout(70, TimeUnit.SECONDS);
Select dropCountry = new Select(driver.findElement(By.id("txtNewLocation")));
dropCountry.selectByVisibleText("India");
driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);
driver.findElement(By.xpath("//button[#class='btn']/label")).click();
driver.manage().timeouts().implicitlyWait(70, TimeUnit.SECONDS);
driver.manage().timeouts().pageLoadTimeout(70, TimeUnit.SECONDS);
Thread.sleep(10000);
driver.findElement(By.xpath("//li[#class='icon-button add']/span")).click();
driver.findElement(By.xpath("//div[#id='ENCActions']/a/label")).click();
driver.findElement(By.xpath("//label[starts-with(text(),'Create Part...')]")).click();
driver.manage().timeouts().implicitlyWait(70, TimeUnit.SECONDS);
driver.manage().timeouts().pageLoadTimeout(70, TimeUnit.SECONDS);
String parentWindowHandler = driver.getWindowHandle(); // Store your parent window
String subWindowHandler = null;
Set<String> handles = driver.getWindowHandles(); // get all window handles
Iterator<String> iterator = handles.iterator();
while (iterator.hasNext()){
subWindowHandler = iterator.next();
}
driver.switchTo().window(subWindowHandler); // switch to popup window
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = driver.findElement(By.xpath("//select[#id='Type-Field']//following-sibling::div//div//input"));
element.click();
Thread.sleep(3000);
element.sendKeys(Keys.BACK_SPACE);
Thread.sleep(3000);
element.sendKeys("Subassy");
Thread.sleep(4000);
driver.findElement(By.xpath("//div[#data-value='Subassy']")).click();
driver.findElement(By.xpath("//span[text()='Description']//parent::td//following-sibling::td//textarea")).sendKeys("Testing");
driver.findElement(By.xpath("//option[text()='BioSc-DS-Chemical']//parent::select")).click();
Thread.sleep(2000);
driver.findElement(By.xpath("//option[text()='BioSc-DS-Chemical']")).click();
driver.findElement(By.xpath("//a[text()='Done']")).click();
driver.switchTo().window(parentWindowHandler);
driver.manage().timeouts().implicitlyWait(70, TimeUnit.SECONDS);
driver.manage().timeouts().pageLoadTimeout(70, TimeUnit.SECONDS);
wait = new WebDriverWait(driver, 60);
element = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//a[#title='Part Details']")));
element.click();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return driver;
}
This is the html code of the element, I am unable to find.
<div class="tabcontent">
<a class="tablink" href="javascript:void(0);" title="Part Details"
onclick="tvcTabPage_tabClicked(this,true)">Part Details</a>
<a href="javascript:void(0);" class="closetab"
onclick="tvcTabPage_tabClosed(this)" title="Close Tab"></a>
</div>
This is the stack trace
Exception in thread "main" org.openqa.selenium.TimeoutException: Expected
condition failed: waiting for element to be clickable: By.xpath:
//a[#title='Part Details'] (tried for 60 second(s) with 500 MILLISECONDS
interval)
Caused by: org.openqa.selenium.NoSuchElementException: Cannot locate an
element using By.xpath: //a[#title='Part Details']
Even though I have used wait statement. I am unable to locate the element. I have verified the xpath using chrome xpath. Please help me resolving my issue.
Selenium version:3.3.1. The actual flow is, I am clicking a link in main page which results a popup consisting a form. After filling the form and clicking on done, popup gets closed automatically and main page gets refreshed and a new page is opened. Now, I am trying to click on the Part Details link in the new main page which is not working.
I have added this peice of code to find the right window handler.
subWindowHandler = null;
Set<String> handles1 = driver.getWindowHandles(); // get all window handles
iterator = handles1.iterator();
while (iterator.hasNext()){
subWindowHandler = iterator.next();
driver.switchTo().window(subWindowHandler);
element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//a[#title='Part Details']")));
System.out.println("KK1");
}
Giving me the output:
Exception in thread "main" org.openqa.selenium.TimeoutException: Expected
condition failed: waiting for visibility of element located by By.xpath:
//a[#title='Part Details'] (tried for 10 second(s) with 500 MILLISECONDS
interval)
Here, required 'Part Details' element is located in a frame which I have included in code. But, i am unable to locate the element inside the frame.
This is my modified code.
System.out.println(driver.switchTo().window(parentWindowHandler).getTitle());
driver.switchTo().frame("content");
driver.switchTo().frame("detailsDisplay");
driver.findElement(By.xpath("//a[#title='Part Details']")).click();
But I am facing this error.
Exception in thread "main" org.openqa.selenium.NoSuchElementException: no
such element: Unable to locate element:
{"method":"xpath","selector":"//a[#title='Part Details']"}
I have attached my screenshot of the html code.
HTML screenshot
Change visibilityOfElementLocated instead of elementToBeClickable.
You can directly find the webeelement, and then click on it as shown below:
element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//a[#title='Part Details']")));
To invoke click() on the link with text as Part Details you need to induce WebDriverWait and invoke click() as follows :
linkText :
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.linkText("Part Details"))).click();
cssSelector :
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("a.tablink[title='Part Details']"))).click();
xpath :
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//a[#class='tablink' and #title='Part Details']"))).click();
your parentWindowHandler should not be correct, you fetch it at wrong time point.
Try move below code line to the first line in the try block
try {
String parentWindowHandler = driver.getWindowHandle(); // Store your parent window
Once switched to parent window, try to refresh the page then find the element as given below. It may solve your issue.
driver.switchTo().window(parentWindowHandler);
driver.navigate().refresh();
driver.manage().timeouts().implicitlyWait(70, TimeUnit.SECONDS);
driver.manage().timeouts().pageLoadTimeout(70, TimeUnit.SECONDS);
wait = new WebDriverWait(driver, 60);
element = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//a[#title='Part Details']")));
element.click();

Unable To Click Paypal Button Continue With Selenium

My code begins by signing me into PayPal, then signing into eBay and navigating to the pay fees page, then checking out with PayPal. The final "Continue" button I can't click/submit. I've tried by xpath, id and class. I even tried sending TAB 7x until the Continue button and then sending Enter but that didn't work.
I have found this discussion but I'm not sure how to make it work for me.
PayPal Sandbox checkout 'continue button' - Unable to locate element: - C# WebDriver
Here's a screenshot of the PayPal code and page I'm trying to do.
//Chrome WebDriver specific
System.setProperty("webdriver.chrome.driver", "C:\\automation\\drivers\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize(); //maximise webpage
WebDriverWait wait = new WebDriverWait(driver, 20);
//navigate to Paypal
driver.get("https://www.paypal.com/uk/signin");
//wait 2.5s for the page to load
try {
Thread.sleep(2500);
}
catch (Exception e) {
e.printStackTrace();
}
WebElement paypalEmail = driver.findElement(By.id("email"));
paypalEmail.sendKeys("******");
//wait 2.5s for the page to load
try {
Thread.sleep(2500);
}
catch (Exception e) {
e.printStackTrace();
}
WebElement paypalSubmit = driver.findElement(By.id("btnNext"));
paypalSubmit.click();
String URL = ("https://www.paypal.com/uk/signin");
driver.get(URL);
WebElement form2 = driver.findElement(By.cssSelector(".main form"));
WebElement username = form2.findElement(By.id("password"));
username.sendKeys("******");
WebElement paypalSubmit2 = driver.findElement(By.id("btnLogin"));
paypalSubmit2.click();
//navigate to Ebay
driver.get("https://signin.ebay.co.uk/ws/eBayISAPI.dll?SignIn&ru=https%3A%2F%2Fwww.ebay.com%2F");
// Enter user name , password and click on Signin button
WebElement form = wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("#mainCnt #SignInForm")));
form.findElement(By.cssSelector("input[type=text][placeholder='Email or username']")).sendKeys("******");
form.findElement(By.cssSelector("input[type=password]")).sendKeys("******");
form.findElement(By.id("sgnBt")).click();
driver.get("http://cgi3.ebay.co.uk/ws/eBayISAPI.dll?OneTimePayPalPayment");
//WebElement Pay =
driver.findElement(By.xpath("//input[#value='Pay']")).click();
WebDriverWait wait2 = new WebDriverWait(driver, 15);
wait2.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[#id=\"confirmButtonTop\"]")));
driver.findElement(By.xpath("//*[contains(#id,'confirmButtonTop')]")).click();
}
}
Based on your given screenshot one of following should work to click on continue button :
Method 1 :
WebElement paypalSubmit = driver.findElement(By.xpath("//input[#data-test-id='continueButton']"));
paypalSubmit.click();
Method 2:
By paypalButton=By.xpath("//input[#data-test-id='continueButton']"));
WebElement element=driver.findElement(paypalButton);
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].scrollIntoView(true);",element);
js.executeScript("arguments[0].click();", element);
Try 2nd method if you feel your button require bit scroll to bottom to get clickable.
one more xpaths you can use for button if above don't work :
//input[#value='Continue' and #id='confirmButtonTop']
In my experience, paypal likes to use iFrames. If that's true in your case, that means unless you tell webdriver to switch frame contexts, that paypal form will be unavailable to you regardless of your xpath/css selectors.
You can get a list of all available frames currently loaded with this code:
String[] handles = driver.getWindowHandles()
Your actual page will always be the 0th index in that returned array. If paypal is your only iFrame, then you can target the 1th index. Here's a possible solution to that:
String mainPageHandle = handles[0];
String paypalHandle = handles[1];
driver.switchTo().window(paypalHandle);
// Do paypal interactions
driver.switchTo().window(mainPageHandle);
// Back to the main page
There are definitely more robust ways to handle this, and if your page unfortunately has more than one iFrame, then you may need to do more to verify which handle is which, such as test the presence of an element you know is contained within. In general, the frames will load in the same order every time. As a golden path to this problem, this will get you in and out of that iFrame to perform work.
Sometimes the conventional click() doesn't work. In that case, try using the Javascript Executor Click as below.
Make sure you import this class
org.openqa.selenium.JavascriptExecutor
And use this instead of click();
JavascriptExecutor executor = (JavascriptExecutor) driver;
executor.executeScript("arguments[0].click();", driver.findElement(By.xpath(“//input[#data-test-id='continueButton']”)));
Try this and let me know if this works for you.

Program terminates entering pass into textbox with webrunner

public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C://chromedriver//chromedriver.exe");
WebDriver driver = new ChromeDriver();
//Maximize the Browser window
driver.manage().window().maximize();
driver.get("https://google.com");
WebElement signin = driver.findElement(By.id("gb_70"));
signin.click();
WebElement username = driver.findElement(By.id("Email"));
username.sendKeys("email#gmail.com");
WebElement next = driver.findElement(By.id("next"));
next.click();
WebElement password = driver.findElement(By.id("Passwd"));
password.sendKeys("password");
WebElement next1 = driver.findElement(By.id("signIn"));
next1.click();
My program terminates when it gets to the password entry screen.. it says
Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"id","selector":"Passwd"}
(Session info: chrome=53.0.2785.143)
However, I have tried ID element and Xpath element and they are both correct
:
(
Possibly you need to wait after next.click(); command. After clicking next button, your input filed is not loaded yet. So, wait for the element to get loaded and put text in it.
Edit:
You can use explicit wait for this. It's better way then Thread.sleep(). Specify a maximum time to wait for element. If the specified time elapsed before your element is visible then it will throw a exception.
Code snippet:
WebDriverWait wait = new WebDriverWait(driver, 30); // waiting for maxiumum of 30 seconds
wait.until(ExpectedConditions.presenceOfElementLocated(By.id("Password")));

Categories