Consider the below code:
getCurrentUrl(driver);
driver.close();
getCurrentUrl(driver);
public void getCurrentUrl (WebDriver driver) {
if (driver window is not closed)
System.out.println(driver.getCurrentUrl());
else
System.out.println("Window is not available");
}
Please let me know how to perform the "driver window is not closed" check in Java.
hmmm ... Consider this just as a guess. But I feel like that when you call driver variable after you close it, you can get NullPointerException because it will be null
But anyway. I would implement it like this:
public void getCurrentUrl (WebDriver driver) {
try {
System.out.println(driver.getCurrentUrl());
} catch (Exception e) { // the most top one
System.out.println("Window is not available");
}
}
There is possibly better and cleaner way of doing it. But I am not Java programmer and my gut feeling tells me this will work
Related
I'm trying to move to a different page (click 'my account'), and a floating advertisement appears:
advertisement
I tried to click on it, and can't find the "Close" element.
Found that it might related to frames, but still not works.
My Code:
public void clickMyAccount() {
driver.findElement(myAccountBtn).click();
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(10));
try {
Thread.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void clickCloseAd(){
driver.switchTo().frame(driver.findElement(By.id("google_esf")));
driver.switchTo().frame(driver.findElement(By.id("aswift_9")));
driver.switchTo().frame(driver.findElement(By.id("ad_iframe")));
driver.findElement(By.id("dismiss-button")).click();
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(10));
driver.switchTo().defaultContent();
}
Site:
https://practice.automationtesting.in/
Any idea how can I click the floating advertisement?
Tried: move between frames until able to find the Close element
Actual: still can't find this element
It is hard to handle advertisement popUp. So we can handle it in 2 ways:
downloading ad-blocker extension to your chrome and using the chrome option code.
download ad-bocker- https://chrome.google.com/webstore/detail/adblock-%E2%80%94-best-ad-blocker/gighmmpiobklfepjocnamgkkbiglidom
use chromeoption driver code:
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("disable-infobars");
Notice that popUp gets disabled is do back. so we can is click on myaccount go back and then click back:
WebElement MyAccount = driver.findElement(By.xpath("//[#href='https://practice.automationtesting.in/my-account/']"));
MyAccount.click();
driver.navigate().back();
MyAccount.click();
Found the issue:
My 'wait' not always working, so the driver tries to close the ad when not displayed - still searching for a way to correct this
It's working without frame1: "google_esf", only frame2 and frame3 needed
Updated code:
public void clickMyAccount() {
System.out.println("Click My Account");
if(driver.findElement(myAccountBtn).isDisplayed()){
driver.findElement(myAccountBtn).click();
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(10));
} else {
System.out.println("My account button not displayed");
}
}
public void clickCloseAd(){
System.out.println("Click Close Ad");
if(driver.findElement(By.id("aswift_9")).isDisplayed()){
// driver.switchTo().frame(driver.findElement(By.id("google_esf"))); //Not in use but also a frame
driver.switchTo().frame(driver.findElement(By.id("aswift_9")));
driver.switchTo().frame(driver.findElement(By.id("ad_iframe")));
driver.findElement(By.id("dismiss-button")).click();
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(10));
driver.switchTo().defaultContent();
} else {
System.out.println("Ad not displayed");
}
}
Thanks all!
After answers given by Anand and Prophet, I made the changes in the code but now it is not validating the test results whether the account got created or not. Ideally, it should validate whether after giving all the required information account got created or not. I am not sure where it went wrong please help me on the same.
package Seleniumtesting;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class Selenium {
ChromeDriver driver;
String url ="https://login.mailchimp.com/signup/";
public void invokeBrowser() {
try {
System.setProperty("webdriver.chrome.driver","C:\\Users\\hp\\Desktop\\Selenium\\chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
TimeUnit.SECONDS.sleep(2);
driver.get(url);
String urlFromWebpage = driver.getCurrentUrl();
if(urlFromWebpage.equals("https://login.mailchimp.com/signup/")) {
System.out.println("PASS");
}
else {
System.out.println("FAIL");
}
}
catch(InterruptedException ex)
{
ex.printStackTrace();
}
}
public void signup(){
try {
WebElement createAccountHeading = driver.findElement(By.xpath("//span[text()='Create an account or ']"));
if(createAccountHeading.isDisplayed()) {
System.out.println("PASS");
}else
System.out.println("FAIL");
driver.findElement(By.name("email")).sendKeys("Testvina12435#gmail.com");
driver.findElement(By.name("username")).sendKeys("Testvina1243");
driver.findElement(By.name("password")).sendKeys("Test123#");
TimeUnit.SECONDS.sleep(2);
driver.findElement(By.name("marketing_newsletter")).click();
TimeUnit.SECONDS.sleep(2);
//driver.findElement(By.xpath("//button[#id='create-account']")).click();
driver.findElement(By.xpath("//*[#id=\"create-account\"]")).click();
TimeUnit.SECONDS.sleep(2);
String u = driver.getCurrentUrl();
System.out.println("URL: "+u);
/*if(u.equalsIgnoreCase("https://login.mailchimp.com/signup/success/"))
{
System.out.println("PASS !! Account created successfully");
}
else
{
System.out.println("FAIL !! It might have not met the criteria");
}*/
driver.close();
}
catch(InterruptedException ex)
{
ex.printStackTrace();
}
}
public static void main(String[] args) {
Selenium mc = new Selenium();
mc.invokeBrowser();
mc.signup();
}
}
This you can use for Sign up:
driver.find_element(By. ID, "create-account").click()
The caveat is that it gets enabled only when the password criteria is met with, which for mailchimp is at least (as per the website) : 1 lower character, 1 upper character, 1 number, 1 special character, and minimum password length is 8.
I see you used your password as 'Test123' which would not enable the button, as the set criteria is not met. Please check the password rules given just below the password input box of the website.
UPDATE:
Per your latest comment, I am updating here.
I see that when I tested, it redirects to another page where it asks for email confirmation.
https://login.mailchimp.com/signup/success/?username=Test1243&userId=168758830&loginId=181489470
Now, there is /success/ in it. And I suppose you are using this page to assert that your act was successful; in which case, I would say that you used .equals in your code, which fails it as there is more to the url than you are looking for, so it should not be .equals, but it should something be like .contains or something like that (I do not know what Java uses, so please search for that equivalent keyword)
UPDATE (Java code edit of #vicky per request)
public void signup(){
try {
WebElement createAccountHeading = driver.findElement(By.xpath("//span[text()='Create an account or ']"));
if(createAccountHeading.isDisplayed()) {
System.out.println("PASS");
}else
System.out.println("FAIL");
driver.findElement(By.name("email")).sendKeys("Testvina12435#gmail.com");
driver.findElement(By.name("username")).sendKeys("Testvina1243");
driver.findElement(By.name("password")).sendKeys("Test123#");
TimeUnit.SECONDS.sleep(2);
// code edit by #anandgautam
driver.findElement(By.xpath("//div[#id='onetrust-close-btn-container")).click();
TimeUnit.SECONDS.sleep(1);
driver.findElement(By.name("marketing_newsletter")).click();
TimeUnit.SECONDS.sleep(5);
// end of code edit by #anandgautam
//driver.findElement(By.xpath("//button[#id='create-account']")).click();
driver.findElement(By.xpath("//*[#id=\"create-account\"]")).click();
TimeUnit.SECONDS.sleep(2);
String u = driver.getCurrentUrl();
System.out.println("URL: "+u);
/*if(u.equalsIgnoreCase("https://login.mailchimp.com/signup/success/"))
{
System.out.println("PASS !! Account created successfully");
}
else
{
System.out.println("FAIL !! It might have not met the criteria");
}*/
driver.close();
}
catch(InterruptedException ex)
{
ex.printStackTrace();
}
}
Your password is missing a special character. The Sign Up button not appearing on that page until you filled all the fields with valid data.
So if you change your password from Test123 to f.e. Test123$ you will be able to see, locate and click the Sing Up button with this code:
driver.findElement(By.xpath("//button[#id='create-account']")).click();
I have automation scenario that sometimes the system return javascript alert and sometimes not at all. I don't know what the cause of this, probably the network issue. I already create the alert handler for this:
public boolean isAlertPresent() {
WebDriverWait wait = new WebDriverWait(driver, 5);
wait.until(ExpectedConditions.alertIsPresent());
return true;
}
I call this in one of my step that sometimes appear alert:
public WSSPage enterAndSearchContent(String title) throws InterruptedException {
waitForElementTextWithEnter(searchTextField, title);
while (isAlertPresent()){
Alert alert = driver.switchTo().alert();
alert.dismiss();
break;
}
return PageFactory.initElements(driver, WSSPage.class);
}
The problem is when the alert doesn't show up, it will give me NoAlertPresentException, and the automation result will be failed. I want the code to move on if the alert doesn't happen by moving to the next line, in this case it will just return PageFactory.initElements(driver, WSSPage.class);
Can you help me provide a better code from this?
Thanks a lot.
JavascriptExecutor worked for you. Just take care that you should execute it before clicking the event which invoke alert.
((JavascriptExecutor) driver).executeScript("window.confirm = function(msg) { return true; }");
Note :- do not use it after clicking on event which invoke alert confirmation box. Above code by default set the confirmation box as true means you are accepting/click on ok on all confirmation box on that page if invoked
Hope it will help you :)
You can modify the method isAlertPresent as given below and try it. It may help you.
public boolean isAlertPresent() {
try{
WebDriverWait wait = new WebDriverWait(driver, 5);
wait.until(ExpectedConditions.alertIsPresent());
return true;
}
catch (NoAlertPresentException noAlert) {
return false;
}
catch (TimeoutException timeOutEx){
return false;
}
}
You can include that particular exception in try catch. Then the exception will be catched and will not through any error and your execution will continue.
Also create a implicit wait to handle this with less timestamp.
I know there are several threads regarding this topic, but I am not necessarily looking for a solution, but rather an explanation. I work on a very large automation suite that tests a web application via mobile phones using browserstack. My stability is very low.. and it is due to this error getting thrown at me! Occasionally it will work and occasionally it will not.. I can not use Actions because Browserstack does not support that.. WHY does this error exist and has anyone had any success it working around it. I always wait for an object using wait.until(ExpectedConditions), but sometimes this does not work well enough. I cant quite catch it as an exception since it is an Unknown error. Also, our standards do not allow for a Thread.sleep(). Any ideas? Thank you so much
And here is a screen of some code..
You are waiting for a WebElement to be clickable, then again you are finding a list of WebElements and clicking the first element.
This does not guarantee that you are clicking the element you waited for it be clickable.
public void waitAndClickElement(WebElement element) {
driverWait.until(ExpectedConditions.elementToBeClickable(element)).click();
}
In your case,
public void clickImageView() {
driverWait.until(ExpectedConditions.elementToBeClickable(listImageView)).click() ;
}
Element is normally not click able due to following reasons .
Html is loading and client is still receiving updates from server
When Scrolling
It can be due to some object is overlapping target
problem 3 can not be resolved you need to fix your code in this wait i wait for HTML to ready and then verify is it click able or not this has eliminated such exceptions from my code
how ever i made a solution for problem 1 and 2 you can simply use my custom wait before clicking . call this function
public static void waitForElementPresent(final By by, int timeout,WebDriver driver)
After this if you are using browser other then chrome then call Scroll to that object this would fix you problem
Code
public static void waitForElementPresent(final By by, int timeout,WebDriver driver) {
waitForPageLoad(driver);
WebDriverWait wait = (WebDriverWait)new WebDriverWait(driver,40).ignoring(StaleElementReferenceException.class);
/* wait.until(new ExpectedCondition<Boolean>(){
#Override
public Boolean apply(WebDriver webDriver) {
WebElement element = webDriver.findElement(by);
return element != null && element.isDisplayed();
}
}); */
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
wait.until(ExpectedConditions.presenceOfElementLocated(by));
wait.until(ExpectedConditions.elementToBeClickable(by));
WebDriverWait wait2 = new WebDriverWait(driver, 40);
wait2.until(ExpectedConditions.elementToBeClickable(by));
}
//wait for page to laod
public static void waitForPageLoad(WebDriver driver) {
ExpectedCondition<Boolean> pageLoadCondition = new
ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver driver) {
return ((JavascriptExecutor)driver).executeScript("return document.readyState").equals("complete");
}
};
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(pageLoadCondition);
}
This is due to the speed at which selenium runs. It will try and find elements before the page has loaded, thus resulting in this error.
For the code sample you provided, the .until() returns the WebElement you are waiting for. You can use the code below to click it rather than scraping the page again.
public void clickImageView()
{
driverWait.until(ExpectedConditions.elementToBeClickable(listImageView)).click();
}
I am unable to Handle the Print window/popup when I click on a Print button on the Web application. I need to be able to either Close this Window, Click on Print or Cancel. I am not sure whether this is a pop-up or a window.
Could some one help me?
see whether any web elements are visible if you hover the mouse over the popup.
if web elements are visible then its web application pop up
if no web elements are visible then its windows popup
However you can ignore the popup by sending escape key. the following code will work. i just tried, it worked.
public class demo extends parent {
WebDriver driver = new FirefoxDriver();
#Test
public void launch() throws InterruptedException {
driver.get("https://www.google.co.in");
Robot r = null;
try {
r = new Robot();
} catch (AWTException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
WebElement el = driver.findElement(By.xpath(".//*[#id='hplogo']"));
el.click();
Thread.sleep(10000);
el.sendKeys(Keys.CONTROL + "p"); // trying to invoke print pop up
Thread.sleep(10000);
r.keyPress(KeyEvent.VK_ESCAPE); //dismissing it by sending escape keys
}
}
hope you will get some idea here :)