Prompting user input in selenium web driver before launching URL - java

I am trying to take user input then stored into the variable and i want to use that input into my program .
Here is my code , code is asking for user input but not loading the URL . It is just initiating the driver. Please someone correct me .
Current behavior:
Initiating the driver (IE shows the message " This is the Initial start page for wendriver server"
Asking for prompt .I gave my input in the prompt and click OK.
thats it .. after that code is not getting executed. Please help me
enter image description here
public class app{
public static void main(String[] args) throws Throwable
{
System.setProperty("webdriver.ie.driver", "C:\\Automation\\IEDriverServer.exe");
WebDriver driver = new InternetExplorerDriver();
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.promptResponse=prompt('Please enter the USER ID')");
if(isAlertPresent(driver)) {
// switch to alert
Alert alert = driver.switchTo().alert();
// sleep to allow user to input text
Thread.sleep(10000);
// this doesn't seem to work
alert.accept();
String ID = (String) js.executeScript("return window.promptResponse");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("my application URL");
driver.findElement(By.name("USERID")).sendKeys("username");
driver.findElement(By.name("user_pwd")).sendKeys("mypwd");
driver.findElement(By.name("submit")).submit();
.......
......
// some more code which is doing my application fucntionality
.......
......
........
private static boolean isAlertPresent(WebDriver driver) {
try
{
driver.switchTo().alert();
return true;
} // try
catch (NoAlertPresentException Ex)
{
return false;
}
}
}

If you need to take input (ie. URL) from promp then you may use JOptionPane's showInputDialog() method from Java Swing.
Code snippet:
String URL =JOptionPane.showInputDialog(null,"Enter URL");

Try following code; it should serve your purpose:
public class app{
public static void main(String[] args) throws Throwable
{
System.setProperty("webdriver.ie.driver", "C:\\Automation\\IEDriverServer.exe");
WebDriver driver = new InternetExplorerDriver();
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.promptResponse=prompt('Please enter the USER ID')");
isAlertPresent(driver);
String ID = (String) js.executeScript("return window.promptResponse");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("my application URL");
driver.findElement(By.name("USERID")).sendKeys("username");
driver.findElement(By.name("user_pwd")).sendKeys("mypwd");
driver.findElement(By.name("submit")).submit();
}
private static void isAlertPresent(WebDriver driver) {
try
{
driver.switchTo().alert();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); // even though not needed
isAlertPresent(driver);
} // try
catch (NoAlertPresentException Ex)
{
}
}
}

Related

Cucumber-JVM: Parallel execution not exactly parallel

I had coded two features file and each of the features file open different browser URL for example one is open google.com and secnd one open amazon.com but this is not the case.
Bothe browsers open google.com. Moreover, it cannot interact with the browser, any actions coded to the browser is not get executed. Besides this, closing first browser cause second browser has null pointer exception.
Cucumber version 6 I start with AbstractCucumberTesNG inheritance. Then i create Login.Feature and follow by AddProduct.Feature.
The expected behaviour should be one browser open phptravels.net website and another browser open http://sellerceter.lazada.my.
This is not the case with my current situation where it open two browsers with phptravels.net, after cloing one browser it open seller.lazada website.
public class AddProduct {
private WebDriverWait timeWait;
private AddProductPageObject page;
private ChromeDriver driver;
private Logger log = LogManager.getLogger(AddProduct.class);
// ======================================================================
public AddProduct() {
}
#Given("navigate to manage product")
public void navigateToManageProduct() {
log.info("Start Login");
try {
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
this.timeWait = new WebDriverWait(driver, 30);
page = PageFactory.initElements(driver, AddProductPageObject.class);
driver.navigate().to("https://sellercenter.lazada.com.my/apps/seller/login");
timeWait.until(ExpectedConditions.visibilityOfElementLocated(page.getLazadaSellerLogo()));
// Input username
driver.findElement(page.getUsername()).click();
driver.findElement(page.getUsername()).clear();
driver.findElement(page.getUsername()).sendKeys("nicholaswkc34#gmail.com");
// Input password
driver.findElement(page.getPassword()).click();
driver.findElement(page.getPassword()).clear();
driver.findElement(page.getPassword()).sendKeys("wlx_+279295");
// Click submit btn
driver.findElement(page.getSignInButton()).click();
//assertThat(page.getPageTitle())
Wait wait = new Wait();
wait.implicitWait(driver, 5);
} catch (Exception e) {
log.error(e);
}
}
}
public class Login_FE {
private WebDriverWait timeWait;
private LoginPageObject page;
private ChromeDriver driver;
private Logger log = LogManager.getLogger(Login_FE.class);
// ======================================================================
public Login_FE() {
}
#Given("Launch the homepage and login")
public void launchTheHomepageAndLogin() {
log.info("Start Login");
try {
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
timeWait = new WebDriverWait(driver, 30);
// Instantiate LoginPageObject
page = PageFactory.initElements(driver, LoginPageObject.class);
log.info("Navigate to phptravels homepage");
driver.navigate().to("https://www.phptravels.net/admin");
timeWait.until(ExpectedConditions.visibilityOfElementLocated(page.getPhpLogo()));
Actions inputAct = new Actions(driver);
inputAct.sendKeys("admin#phptravels.com").perform();
driver.findElement(page.getUsername()).sendKeys("admin#phptravels.com");
Wait wait = new Wait();
wait.implicitWait(driver, 3);
}catch(Exception e) {
log.error(e);
}
log.info("Login Successfully");
}
}
Im using the same concept for testing mobile apps. So in order to open 2 browsers and to interact with them separately you have to store the driver while initiating in a threadlocal like below :
private static ThreadLocal<AppiumDriver<MobileElement>> appiumDriver = new ThreadLocal<>();

How to confirm the page title using selenium?

#Test(priority = 0)
public void test() throws Exception {
driver.get(baseUrl + "/");
driver.findElement(By.name("email")).clear();
driver.findElement(By.name("email")).sendKeys("lanka#ensiz.com");
driver.findElement(By.name("password")).clear();
driver.findElement(By.name("password")).sendKeys("123456");
driver.findElement(By.xpath("//button[contains(text(),'Sign In')]")).click();
}
#Test(priority = 1)
public void verifyHomepageTitle(){
String expectedTitle = "Placer Admin - Home";
String actualTitle = driver.getTitle();
Assert.assertEquals(actualTitle, expectedTitle);
}
#AfterClass(alwaysRun = true)
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
I'm new to automation testing.I want to make sure the valid user logins.For that i'm trying to verify the title of the page.But my test fail all the time,because it is execute before valid user going to the dashboard.how can I test this?Can i know the proper modifications for this code?
Please help..thanks
What you can do is, on the dashboard page select an element which is always there but is not on the login page. For example, a menu item or maybe a header.
Then create a wait like this at the end of the login test, so the test only completes after the dashboard is loaded:
WebDriverWait wait = new WebDriverWait(driver, 5);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("XPath here")));
This will wait for a max of 5 seconds for the dashboard to load. The syntax could be wrong somewhere as I do everything in C#.
Use this code it is working fine in my machine :
public class User3806999 {
WebDriver driver;
WebDriverWait wait;
#BeforeClass
public void setUpClass(){
System.setProperty("webdriver.chrome.driver", "F:\\Automation\\chromedriver.exe");
driver = new ChromeDriver();
wait = new WebDriverWait(driver,30);
driver.manage().window().maximize();
driver.get("https://test.admin.placer.life/login");
}
#Test()
public void testLogin() throws Exception {
driver.findElement(By.name("email")).clear();
driver.findElement(By.name("email")).sendKeys("lanka#ensiz.com");
driver.findElement(By.name("password")).clear();
driver.findElement(By.name("password")).sendKeys("123456");
driver.findElement(By.xpath("//button[contains(text(),'Sign In')]")).click();
wait.until(ExpectedConditions.visibilityOf(driver.findElement(By.id("user_menu"))));
//Assert something here
}
#Test(dependsOnMethods ={"testLogin"})
public void verifyHomepageTitle(){
String expectedTitle = "Placer Admin - Home";
String actualTitle = driver.getTitle();
Assert.assertEquals(actualTitle, expectedTitle);
}
#AfterClass(alwaysRun = true)
public void tearDown() throws Exception {
//logout here
}
}
Use the explicit wait as below before assertion:
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.titleContains(expectedTitle);

How to quit the page if i type hello world on google search using selenium?

Hi guys I want to quit the page afte I type "Hello World" in google search using firefox browser and selenium
WebDriver driver = null;
public static void main(String args[]) {
SimpleSelenium ss = new SimpleSelenium();
ss.openBrowser();
ss.getPage();
ss.quitPage();
}
private void openBrowser() {
System.setProperty("webdriver.gecko.driver", "C:/geckodriver.exe");
driver = new FirefoxDriver();
}
private void quitPage() {
driver.quit();
}
private void getPage() {
driver.get("http://www.google.com");
}
1) Create a Junit test class
2) Initialize the driver in your setup method like
ChromeDriver driver = new ChromeDriver();//Download chromeDriver.exe file and point to location where you have installed the like as you mentioned. `driver.System.setProperty("webdriver.gecko.driver", "C:/geckodriver.exe");`
3) Create a test method with your business logic to type hello world
3) Create After and Before Class annotations for the methods .In After class annotation method you can write driver.quit.
You can refer to following link for more clarity
https://www.guru99.com/selenium-tutorial.html
I am Added sample format which is written Using java and testNG..Here Every time First before method will run then 1st test case will execute then after method will work then again before method work then next test case......In this way you can manage your test case and it will also generate Report also.Here you will get better explanation.
public class GoogleTest {
FirefoxDriver driver;
#BeforeMethod
public void setUp1() throws Exception {
System.setProperty("webdriver.gecko.driver", "D:\\\\ToolsQA\\trunk\\Library\\drivers\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://www.google.com");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void GoogleInputField() throws InterruptedException {
System.out.println("Hello world");
System.out.println("Hello world");
//Write Your test case for test case 1
}
#Test
public void google suggestion() throws InterruptedException {
//Write Your test case for test case 1
}
#AfterMethod
public void getResult(ITestResult result) throws IOException {
driver.quit();
}
}
Dont forget to add Firefox driver on gecko.driver path
I am assuming that you want to open the browser using selenium, load google and then listen till you MANUALLY enter "hello world" in the input box. The method listenForHelloWorld() will do that.
public static void main(String args[]) {
SimpleSelenium ss = new SimpleSelenium();
ss.openBrowser();
ss.getPage();
ss.listenForHelloWorld();
ss.quitPage();
}
private void listenForHelloWorld() {
// Get the search field
WebElement searchField = driver.findElement(By.name("q"));
int count = 1;
while (count++ < 20) {
// if search field value is "hellwo world" break loop which will eventallu lead to `quit()` as it is the next method to exit.
if (searchField.getAttribute("value").equalsIgnoreCase("hello world")) {
break;
}
Thread.sleep(5000)
}
}
If you are asking how to enter "hello world" in browser automatically use below.
driver.findElement(By.name("q")).sendKeys("hello world");

In frame, how to find username textbox's xpath with webdriver

I want to sign in to http://www.timesjobs.com/. Upon signing in a pop-up appears (it is the css lightbox). Cannot find the exact xpath for the username on this sign-in box. I iterated over each and every frame and tried to use firefox generated xpath for username textbox. I got exception as:
org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"xpath","selector":"//html/body//input[#name='j_username']"}.
Tried below code but no luck:
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(6, TimeUnit.SECONDS);
driver.get("http://www.timesjobs.com");
driver.findElement(By.linkText("Sign In")).click();
Thread.sleep(10000L);
List<WebElement> frames = driver.findElements(By.tagName("iframe"));
System.out.println("Total Frames: " + frames.size());
int k =0;
while(k<=frames.size()){
try{driver.switchTo().defaultContent();
driver.switchTo().frame(k);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
WebElement we1 = driver.findElement(By.xpath("//html/body//input[#name='j_username']"));
we1.sendKeys("xyzusername#xyzcompany.com");
System.out.println("in try BLOCK:"+k);
}catch(Exception e){
e.printStackTrace();
System.out.println("in catch: "+k);
}finally{
k++;}
}
System.out.println("end of the program");
}
Try the following code. It works.
Your username Field is contained within GB_Frame which is contained under GB_Frame1. So we have to switch to GB_Frame1 and then to GB_Frame. Username field has a name, so better use it over xpath.
public static void main(String[] args) throws InterruptedException {
WebDriver driver = new FirefoxDriver();
driver.get("http://www.timesjobs.com");
driver.findElement(By.linkText("Sign In")).click();
Thread.sleep(10000);
driver.switchTo().frame("GB_frame1");
driver.switchTo().frame("GB_frame");
WebElement we1 = driver.findElement(By.name("j_username"));
we1.sendKeys("xyzusername#xyzcompany.com");
}
I dont understand what difficulty you had in identifying the frames. It was pretty clear from the page source. Let me know if this helps you.

"Unable to locate element" exception with WebDriver

I'm getting an "Unable to locate element" exception while running the below code. My expected output is First Page of GoogleResults.
public static void main(String[] args) {
WebDriver driver;
driver = new FirefoxDriver();
driver.get("http://www.google.com");
driver.manage().timeouts().implicitlyWait(45, TimeUnit.SECONDS);
WebElement oSearchField = driver.findElement(By.name("q"));
oSearchField.sendKeys("Selenium");
WebElement oButton = driver.findElement(By.name("btnG"));
oButton.click();
//String oNext = "//td[#class='b navend']/a[#id='pnnext']";
WebElement oPrevious;
oPrevious = driver.findElement(By.xpath("//td[#class='b navend']/a[#id='pnprev']"));
if (!oPrevious.isDisplayed()){
System.out.println("First Page of GoogleResults");
}
}
If I run the above code I get "Unable to Locate Element Exception". I know the Previous Button Element is not in the first page of the Google Search Results page, but I want to suppress the exception and get the output of the next step if condition.
Logical mistake -
oPrevious = driver.findElement(By.xpath("//td[#class='b navend']/a[#id='pnprev']"));
will fail or give error if WebDriver can't locate the element.
Try using something like -
public boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
You can pass the xpath to the function like
boolean x = isElementPresent(By.xpath("//td[#class='b navend']/a[#id='pnprev']"));
if (!x){
System.out.println("First Page of GoogleResults");
}

Categories

Resources