How to know webDriver opened URL successfully - java

How to know WebDriver opened an URL successfully after driver.get(appURL)? I can see it opens nicely in a browser. But I would like to make sure programmatically.
Hey. Here I am asking whether driver.get(appURL) returns any response code like http response. Or I have to find a ID from the web page and find it, then make conclusion, but the approach seems too primitive. I am looking for more simple solution. Someone suggested assertTrue, but some reason Eclipse is giving long error.

The simplest way to do so, would be to assert over the page title of the url you have opened :
String actualTitle = driver.getTitle();
String expectedTitle = "YourExpectedPage"; // replace with the expected page title
org.junit.Assert.assertTrue(expectedTitle.equals(actualTitle));

you can wait some time and check expected result then check current url
String currentURL = null;
WebDriverWait wait = new WebDriverWait(driver, 10);
if(driver.findElement(By.xpath("//*[#id='someID']")).isDisplayed()){ //add id or xpath
currentURL = driver.getCurrentUrl();
System.out.println(currentURL);
}

Each browser has a default error page. For chrome i am using:
if(driver.findElement(By.xpath("//div[#class='error-code']")).isDisplayed()){
MessageBox.Show("chrome error page.");
}

Try this with simple statements
WebDriver driver=new FirefoxDriver();
driver.manage().window().maximize();
String baseUrl="https://stackoverflow.com/";
driver.get(baseUrl);
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
if(baseUrl.equals(driver.getCurrentUrl()))
{
System.out.println("URLS are matching");
}else
{
System.out.println("URLS are not matching");
}

As a End User we really don't have to be concerned about whether WebDriver instance opened an URL successfully or not because once the WebDriver instance requests for a URL, the Browser Client on opening the webpage/website (by default) returns document.readyState as complete to the WebDriver instance and only then our next line of code gets executed.
However, as an End User we can configure the WebDriver instance to act on different available states of the DOM as well. Currently Selenium recognizes document.readyState at 3 different stages as follows:
none - The document is still loading
eager - The document is interactive
normal - The document is complete
Hence our scripts can be written to configure the WebDriver instance to respond as per your requirement.

Related

Selenium chrome driver (Java) click() login button doesn't work programmatically but works manually

I'm just doing some test automation of web UI, specifically this page https://autorefi.capitalone.com/login/
I am locating the lastname, zipcode, ssn input boxes and typing in data (the data here doesn't matter). I am then simply using the locator to click the "Sign In" button. The problem is, everytime I run this within my code (Java) using selenium/chromedriver, I get an error
Sorry, we weren't able to log you in. If you continue to see this error, make sure you're using one of our supported browsers.
The problem is this is not the correct error message. You can try this yourself by simply opening another tab and entering a random lastname, zipcode, and last 4 digit of SSN. Conversely, if you actually had an offer with Capital one, it would bring up a different page completely. The point is, the first error message I posted only comes via selenium and is not correct. The correct error message is:
Sorry, it looks like you don't have an offer with Capital one.
I tried sleeping the thread before clicking the button ,because I thought it was maybe clicking it too fast, but it still didn't work. I a bit perplexed why doing the same set of operations manually seems to work, but launching this programmatically through selenium. Can anyone provide any insight here? My code is:
WebElement element;
WebDriver driver = null;
ChromeOptions options = new ChromeOptions();
options.setPageLoadStrategy(PageLoadStrategy.NONE);
driver = new ChromeDriver(options);
WebDriverManager.getInstance(CHROME).setup();
// TODO: PROD
driver.get("https://autorefi.capitalone.com/login/");
WebElement refiCommonLoginForm = new WebDriverWait(driver,10).until(ExpectedConditions.presenceOfElementLocated(By.tagName("refi-common-login-form")));
WebElement shadowRoot1 = expandRootElement(refiCommonLoginForm, driver);
WebElement refiCommonLastName = shadowRoot1.findElement(By.tagName("refi-common-last-name"));
WebElement refiCommonLastNameShadowRoot = expandRootElement(refiCommonLastName, driver);
WebElement refiCommonZip = shadowRoot1.findElement(By.tagName("refi-common-zip"));
WebElement refiCommonZipShadowRoot = expandRootElement(refiCommonZip, driver);
WebElement refiCommonLastFourSSN = shadowRoot1.findElement(By.tagName("refi-common-last-four-ssn"));
WebElement refiCommonLastFourSSNShadowRoot = expandRootElement(refiCommonLastFourSSN, driver);
refiCommonLastNameShadowRoot.findElement(By.id("loginLastName")).sendKeys("random last name");
refiCommonZipShadowRoot.findElement(By.id("loginZipCode")).sendKeys("43978");
refiCommonLastFourSSNShadowRoot.findElement(By.id("loginLastFourSSN")).sendKeys("3483");
Thread.sleep(2000);
shadowRoot1.findElement(By.tagName("button")).click();
Absolutely not sure the issue is that, but still possibly this will help.
Instead of clicking the "Sign in" button try submitting it i.e. shadowRoot1.findElement(By.tagName("button")).submit()
But I guess the issue here is that this site has some kind of anti bot defense that blocks automated access to it.

How to automate a website login in such a way that we should know each step whether its is executing or not in java...?

I need to automate the 3 click step first login and next page is the pay button, in code i am not getting any error but i am not able to verify that, whether it is executing every step or not, where it is failing, which click is missed out.
Here is my code please review it.
String URL = JsonPath.read(resp, "$..data.amazonPayResponse.amazonPayLoad.paymentRedirectUrl").toString().replaceAll("[\\[\\]\"]", "").replaceAll("\\\\/", "/");
System.out.print("\n=============link==========\n"+URL);
WebDriver driver = new HtmlUnitDriver();
driver.get(URL);
driver.findElement(By.id("ap_email")).sendKeys("1234xxx123");
driver.findElement(By.id("ap_password")).sendKeys("xxxpasswordxxx");
driver.findElement(By.id("signInSubmit")).click();
WebDriverWait wait = new WebDriverWait(driver, 60);
WebElement payNowBtn = wait.until(ExpectedConditions.elementToBeClickable((By.xpath("/html/body/div[1]/div[1]/div[3]/div/div/div[2]/div/div/div/div[2]/div[2]/form/div[2]/div[1]/div[1]/div/span/span/input"))));
payNowBtn.click();
driver.quit();
It is working when I use this path but still it only works in local machine not under Jenkins
By.xpath("//input[#name='ppw-widgetEvent:SetPaymentPlanSelectContinueEvent']")

looking for option to check if page fully loaded with all elements in java for selenium

I am looking for function in Java +selenium where I can check or verify if page is fully loaded. I saw onLoad() of JS but nothing on java, is there is something for JAVA?
also I saw these:
WebDriver driver = new AnyDriverYouWant();
if (driver instanceof JavascriptExecutor) {
((JavascriptExecutor)driver).executeScript("yourScript();");
} else {
throw new IllegalStateException("This driver does not support JavaScript!");
}
but again JS and need to write script in JS
How to use JavaScript with Selenium WebDriver Java
update - also can try these solution too:
void waitForLoad(WebDriver driver) {
new WebDriverWait(driver, 30).until((ExpectedCondition<Boolean>) wd -> ((JavascriptExecutor) wd).executeScript("return document.readyState").equals("complete")); }
from here https://stackoverflow.com/a/15124562/12115696
In order to determine if a page is fully loaded, you will need to identify which WebElements on the page indicate a loading status. For example, if there is a load mask of some type, you will want to wait until the load mask is hidden to verify that the page is fully loaded.
Here's a simple "Wait until loaded" function that utilizes the ExpectedConditions class:
Given the following HTML for a load mask:
<div id='load-mask' style='display: block'/>
You can use the following code to wait until the load mask is hidden:
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(seconds));
wait.Until(ExpectedConditions.InvisibilityOfElementLocated(By.Id("load-mask")));
Edit -- added a JavaScript-only wait function, as requested by the asker:
wait.until(driver=> ((JavascriptExecutor)driver).executeScript("return document.readyState").equals("complete"));
This checks the document.readyState attribute in JavaScript, and completes the wait once readyState is set to complete.

Make Selenium Webdriver Stop Loading the page if the desired element is already loaded?

I am creating a test and having some issues. Here is the scenario. I use Selenium Web driver to fill out a form on Page1 and submit the form by clicking a button. Page2 starts loading... but the problem is, Page2 uses Google Analytics codes, and sometimes it takes forever for the page to stop loading.
Even though the expected element is already present, Selenium web driver does not proceed until the whole web page is fully loaded.
How do I make Selenium to move on to the next task or stop loading external javascript/css if the expected element is already present?
I tried tweaking the following settings but no luck.
driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS);
driver.manage().timeouts().setScriptTimeout(30, TimeUnit.SECONDS);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
TEMPORARY SOLUTION: Scroll below for answer!
Give below approaches a shot.
driver.findElement(By.tagName("body")).sendKeys("Keys.ESCAPE");
or
((JavascriptExecutor) driver).executeScript("return window.stop");
Alternatively, you can also use WebDriverBackedSelenium as shown in the snippet below from Vincent Bouvier.
//When creating a new browser:
WebDriver driver = _initBrowser(); //Just returns firefox WebDriver
WebDriverBackedSelenium backedSelenuium =
new WebDriverBackedSelenium(driver,"about:blank");
//This code has to be put where a TimeOut is detected
//I use ExecutorService and Future<?> Object
void onTimeOut()
{
backedSelenuium.runScript("window.stop();");
}
Source: https://sqa.stackexchange.com/a/6355
Source: https://stackoverflow.com/a/13749867/330325
So, I reported to Selenium about these issues. And the temporary workaround is... messing with Firefox's timeout settings. Basically by default Firefox waits about 250 seconds for each connection before timing you out. You can check about:config for the details. Basically I cranked it down so Firefox doesn't wait too long and Selenium can continue as if the page has already finished loading :P.
Similar config might exist for other browsers. I still think Selenium should let us handle the pagetimeout exception. Make sure you add a star to the bug here: http://code.google.com/p/selenium/issues/detail?id=6867&sort=-id&colspec=ID%20Stars%20Type%20Status%20Priority%20Milestone%20Owner%20Summary, so selenium fixes these issues.
FirefoxBinary firefox = new FirefoxBinary(new File("/path/to/firefox.exe"));
FirefoxProfile customProfile = new FirefoxProfile();
customProfile.setAcceptUntrustedCertificates(true);
customProfile.setPreference("network.http.connection-timeout", 10);
customProfile.setPreference("network.http.connection-retry-timeout", 10);
driver = new FirefoxDriver(firefox, customProfile);
driver.manage().deleteAllCookies();
Once you have checked for the element and you know that it is present, you could either navigate to/load a different page (if the next tasks are on a different page) or if the tasks are on the same page (as you anyway do not need the elements that have not yet loaded), you could continue as usual - selenium will identify the elements which have already been loaded. This works for me when I work with feature rich pages.
Instead of using the webdriver click() to submit the form use jsexecutor and do a click. Jsexecutor does not wait for page load and you can with other actions.
As per the above scenario explained i feel its best to use the below wait command in the first page.
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(ExpectedConditions.presenceOfElementLocated(By.id(>someid>)));
Once the required element is found in the first page next you can proceed to the second page.
As per the above scenario explained i feel its best to use the below wait command in the first page.
WebDriverWait wait = new WebDriverWait(driver, 10); WebElement element =
wait.until(ExpectedConditions.presenceOfElementLocated(By.id(>someid>)));
Once the required element is found in the first page next you can proceed to the second page.
Use explicit/webdriver wait----
WebDriverWait wt=new WebDriverWait(driver, 20);
wt.until(ExpectedConditions.elementToBeClickable(By.name("abc")));

Changing URL using WebDriver

I'm using Selenium WebDriver (Java) and am trying to change the URL after WebDriver has logged into a page.
Is there a way to either:
Change the URL of the current window, or
Open a new tab and go to another page.
Thanks!
You didn't share any code so i don't know how is your approach about it, I only share my knowledge about this subject.
1) For your first question i think you know how to open a new page with selenium web driver maybe you can use some wait method and then invoke the driver again.
//open browser
driver = new FirefoxDriver();
//login
driver.get("https://www.google.com/");
//set implicit wait
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
//Then invoke method again for your second request(I am not try this code maybe you need to create new driver object)
driver.get("https://www.stackoverflow.com");
2) For your second question this link help you.

Categories