I'm VERY new to java\Selenium. What I am trying to achive is test whether our website comes back up after patching, what needs to happen is
1 - open chrome
2 - open url
3 - log in
4 - download pdf
Im trying to catch an error every time my bot hits a roadblock. At the moment i have the below code
What is the best way to write into the code when a bad password prompt pops up on the website
Thanks and sorry if this is such an easy issue
package webdriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import java.io.*;
import java.lang.*;
import java.util.*;
public class launchbrowser {
public static WebDriver driver = null;
public static void main(String[] args) throws IOException {
File file1 = new File("out.txt");
FileWriter fw = new FileWriter(file1);
PrintWriter pw = new PrintWriter(fw);
try {
//Adds driver ver - dont remove
System.setProperty("webdriver.chrome.driver",".\\drivers\\chromedriver78.exe" );
driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(15,TimeUnit.SECONDS);
}
//Catch the Error
catch (Exception e){
pw.println("unable to launch browser");
}
try {
//open webpage and maximizes the window
driver.navigate().to("****Webpage****");
driver.manage().window().maximize();
}
//Catch the Error
catch (Exception e){
pw.println("Unable to open Webpage");
}
try {
//locate Member Number\email
WebElement Username=driver.findElement(By.id("Login.Member number or email"));
Username.sendKeys("****test username****");
}
//Catch the Error
catch (Exception e){
pw.println("Unable to enter username");
}
try {
//locate password
WebElement Password=driver.findElement(By.id("Login.Password"));
Password.sendKeys("****test password****");
}
//Catch the Error
catch (Exception e){
pw.println("Unable to enter password");
}
//Click Login
WebElement Enter=driver.findElement(By.id("Login.Password"));
Enter.sendKeys(Keys.RETURN);
try {
//Download a statement
WebElement Transactions=driver.findElement(By.id("TransactionSummary"));
Transactions.click();
WebElement PDF=driver.findElement(By.linkText("Go"));
PDF.click();
}
catch (Exception e){
pw.println("Unable to download statement");
}
pw.close();
}
}
There are 2 ways to achieve, depending on what you want to test:
Find your pop up element using explicit wait, if it doesn't show up, your explicit wait will throw an exception, which means your password might be valid.
Determine your password is valid or not, then you will decide whether you need to find pop up element.
In the 1st option, I assumed that your validation had worked perfectly. And the 2nd one is checking that your validation worked properly.
Related
I am a total noob at Automation Testing and i am trying to learn through Youtube how to do it.
https://youtu.be/FRn5J31eAMw?t=12405
On this course from Edureka there is an example where they are trying to handle an exception, where after they run the script the system shows them a message in the console which i cannot get.
package co.edureka.selenium.demo;
import java.util.NoSuchElementException;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class HandlingExceptions {
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "C:\\Selenium\\chromedriver_win32\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.google.com");
Thread.sleep(3000);
try {
driver.findElement(By.name("fake")).click();
}catch (NoSuchElementException e) {
System.out.println("element is not found");
System.out.println("Hello");
//throw(e);
}
System.out.println("Hello");
}
}
this is the script in Java they are running and at the end in the console they are getting this as a result
Edureka Console
But i am getting something totally different even though my code is exactly the same.
My Console
What am i doing wrong?
your are using "import java.util.NoSuchElementException;
" at top of file so please remove and use below one
org.openqa.selenium.NoSuchElementException
I have written the following code in JAVA using Selenium web driver using both Internet Explorer and Firefox. Everytime I am getting the same error. Tried using both "id" and "xpath" method, but still it is failing. Tried adding some delay also, still does not work.
My JAVA code for Firefox:
package ieconnector;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.RemoteWebDriver;
public class FireFoxConnector {
public static void main(String[] args) {
try{
GetBrowserProperty gbp = new GetBrowserProperty();
System.setProperty("webdriver.ie.driver",gbp.getIeConnection());
System.setProperty("webdriver.gecko.driver","D:\\softwares\\Selenium\\geckodriver-v0.21.0-win64\\geckodriver.exe");
WebDriver wb = new FirefoxDriver();
Capabilities caps = ((RemoteWebDriver) wb).getCapabilities();
System.out.println("Caps is "+caps);
wb.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
//wb.navigate().to("https://somewebsite.com:22222/SSO/ui/SSOLogin.jsp");
wb.get("https://somewebsite.com:22222/SSO/ui/SSOLogin.jsp");
wb.manage().deleteAllCookies();
wb.manage().window().maximize();
//wb.findElement(By.id("usertxt")).sendKeys(("user").toUpperCase());
//wb.findElement(By.className("passtxt")).sendKeys("password");
//WebDriverWait wait = new WebDriverWait(wb,10);
//WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("usertxt")));
wb.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
//wb.findElement(By.id("usertxt")).sendKeys("USER");
wb.findElement(By.xpath("//*[#id='usertxt']")).sendKeys("USER");
System.out.println("Testing is successful");
} catch (Exception e) {
e.printStackTrace();
}
}
}
And the following is a screenshot of the HTML code in my developer tool in IE/Firefox.
As per the HTML you have shared to locate the User ID field you can use the following solution:
cssSelector:
wb.findElement(By.cssSelector("input.txtbox#usertxt")).sendKeys("USER");
xpath:
wb.findElement(By.xpath("//input[#class='txtbox' and #id='usertxt']")).sendKeys("USER");
This is the second post on Stack Overflow on my quest to access this godforsaken website: https://portal.mcpsmd.org/guardian/home.html
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
public class WebAccessor {
public static void main(String[] args) {
WebDriver driver = new HtmlUnitDriver();
driver.get("https://portal.mcpsmd.org/public/");
System.out.println(driver.getCurrentUrl());
// Find the text input element by its name
WebElement username = driver.findElement(By.id("fieldAccount"));
WebElement password = driver.findElement(By.id("fieldPassword"));
// Enter something to search for
username.sendKeys("");
password.sendKeys("");
WebElement submitBtn = driver.findElement(By.id("btn-enter"));
submitBtn.click();
System.out.println(driver.getCurrentUrl());
driver.quit();
}
}
This code is tested and works on Facebook
I am sure that my button is being pressed as when I click submit, the site URL changes from
https://portal.mcpsmd.org/public/
to
https://portal.mcpsmd.org/guardian/home.html
When I type in usernames and passwords, (actual user and pass cannot be disclosed for obvious reasons), the password line actually tacks on another 20 or so characters to the end of the password field. (You can see this by typing in any random username and password and clicking submit).
This has lead me to believe there is some sort of front-end encryption going on. Is there any feasible way to log in?
Many thanks in advance.
due to lack of credentials, my answer is just a bet.
But i think you should redirect after login, with a little tweak to avoid exceptions, like this:
import java.io.IOException;
import java.net.MalformedURLException;
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
public class WebAccessor {
public static void main(String[] args) {
WebClient WEB_CLIENT = new WebClient(BrowserVersion.CHROME);
WEB_CLIENT.getCookieManager().setCookiesEnabled(true);
HtmlPage loginPage;
try {
loginPage = WEB_CLIENT.getPage("https://portal.mcpsmd.org/public/");
HtmlForm loginForm = loginPage.getFirstByXPath("//form[#id='LoginForm']");
loginForm.getInputByName("account").setValueAttribute("YOURPASSWORD");
loginForm.getInputByName("pw").setValueAttribute("YOURPASSWORD");
loginForm.getElementsByTagName("button").get(0).click();
HtmlPage landing = WEB_CLIENT.getPage("https://portal.mcpsmd.org/guardian/home.html#/termGrades");
System.out.println(landing.getTitleText());
} catch (FailingHttpStatusCodeException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
}
}
}
My output is: Student and Parent Sign In. But if you set correct attributes, it should be ok.
I am trying to use phantomjs for testing, I have one login page with obvious two parameters username and password. If i try same code with google url where i have to pass only one element with and say element.submit(); but in my login page i want to pass two elements how to achieve the same ?
here is my code -
import java.io.File;
import java.io.IOException;
import org.apache.maven.shared.utils.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.phantomjs.PhantomJSDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.Test;
public class PhantomExample {
public PhantomExample() {
System.out.println("this is constructor");
}
#Test
public void verify() {
File src = new File("C:\\Users\\Admin\\Downloads\\Compressed\\phantomjs-2.1.1-windows\\bin\\phantomjs.exe");
DesiredCapabilities phantomjsCap = new DesiredCapabilities();
phantomjsCap.setJavascriptEnabled(true);
phantomjsCap.setCapability("phantomjs.binary.path", src.getAbsolutePath());
System.out.println("inside the verify method");
System.setProperty("phantomjs.binary.path", src.getAbsolutePath());
WebDriver driver = new PhantomJSDriver(phantomjsCap);
driver.get("http://localhost:8080/MyApp/Login");
System.out.println(driver.getPageSource());
WebElement el =driver.findElement(By.name("username"));
WebElement elp =driver.findElement(By.name("password"));
el.sendKeys("username");
elp.sendKeys("0");
el.submit();
elp.submit();
System.out.println(driver.getTitle());
System.out.println(driver.getCurrentUrl());
System.out.println(driver.getPageSource());
File Ss=((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
try {
FileUtils.copyFile(Ss, new File("d:/sample.jpg"));
}
catch (IOException e) {
System.out.println(e.getMessage());
}
driver.quit();
}
}
Here i created two separate elements and expecting to get the response, but when i run it in debugger mode it is not executing after line el.submit();
I am quite sure that i am doing this wrong way, but can someone tell me what is the right approach to this and explain how to get response object which server would send after log in ?
Calling the submit() method on an input field submits the whole form (with all input values), so the following line can be deleted:
elp.submit();
If the form has a submit button, then after executing el.submit() login will be done.
Till yesterday the below mentioned code was working fine but now i am facing some problem .
The code opens firefox browser then loads facebook.com but the code is not sending
email and password to web browser i.e. sendkeys() is not working.
I verified the id of both textbox of email and password which are correct yet code is not working .
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.WebDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
public class Webdriver2 {
WebDriver driver ;
JavascriptExecutor jse;
public void invokeBrowser()
{
try
{
System.setProperty("webdriver.gecko.driver","C:\\geckodriver-v0.19.0-win64\\geckodriver.exe");
driver = new FirefoxDriver();
driver.manage().deleteAllCookies();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS );
driver.get("https://www.facebook.com/");
search();
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
public void search()
{
try
{
driver.findElement(By.id("email")).sendKeys("example#gmail.com");
Thread.sleep(4000);
driver.findElement(By.id("pass")).sendKeys("password");
Thread.sleep(4000);
driver.findElement(By.id("u_0_2")).click();
Thread.sleep(4000);
/*driver.findElement(By.name("q")).sendKeys("spit mumbai");
Thread.sleep(4000);
driver.findElement(By.xpath(" //button[#aria-label='Search' and #data-testid='facebar_search_button'] ")).click();*/
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Webdriver2 w = new Webdriver2();
w.invokeBrowser();
}
}
Try clicking on the two textboxes before you are performing the sendKeys:
driver.findElement(By.id("email")).click();
driver.findElement(By.id("email")).sendKeys("example#gmail.com");
The textboxes probably needs focus.
We need to take care of a couple of things here as follows:
The Email or Phone field is within an <input> tag so we need to take it into account while selecting the locator.
The Password field is also within an <input> tag so we need to take it into account while selecting the locator.
If you observe closely the id of the Log In button is dynamic and also within an <input> tag, so we need to consider this factor as well.
Here is the minimum sample code block using cssSelector to access the url https://www.facebook.com/, provide Email or Phone and Password, finally click on Log In button:
package demo;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Facebook_Login_CSS_FF {
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver", "C:\\Utility\\BrowserDrivers\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://www.facebook.com/");
driver.findElement(By.cssSelector("input#email")).sendKeys("Ryusei");
driver.findElement(By.cssSelector("input[name='pass']")).sendKeys("Nakamura");
driver.findElement(By.cssSelector("input[value='Log In']")).click();
}
}