Condition for incorrect password selenium java - java

My code. I enter my login and password in the "userId" and "password" fields. And I would like to write a condition that will check when you hit the "Submit" button or it is possible to login to the system. If "userId" and "password" are correct, then when you press the "Submit" button a new page loads and the next part of the code is posted. But I would like to add a condition when the user gives a bad password. Then, after pressing the "Submit" button, the message "Bad login information" appears on the page. Can anyone help me write such a condition?
for(int i =0;i<userName.size();i++){
driver.findElement(By.id("userId")).sendKeys(userName.get(i));
Thread.sleep(6000);
driver.manage().timeouts().implicitlyWait(100, TimeUnit.SECONDS);
driver.findElement(By.id("password")).sendKeys(password.get(i));
Thread.sleep(6000);
driver.manage().timeouts().implicitlyWait(100, TimeUnit.SECONDS);
driver.findElement(By.id("Submit")).click();
// Here load new page
// change password
driver.findElement(By.xpath(".//*[#id='_id9']/table/tbody/tr[2]/td[1]/table[1]/tbody/tr[5]/td[2]/a")).click();
driver.manage().timeouts().implicitlyWait(100, TimeUnit.SECONDS);
Thread.sleep(6000);
driver.manage().timeouts().implicitlyWait(100, TimeUnit.SECONDS);
// new password
String pwd = RandomStringUtils.random( 15, upper+smaller+number+character);
System.out.println("New password: " + pwd);
driver.findElement(By.id("newPassword")).sendKeys(pwd);
Thread.sleep(6000);
driver.manage().timeouts().implicitlyWait(100, TimeUnit.SECONDS);
// confirm password
driver.findElement(By.id("confirmPassword")).sendKeys(pwd);
System.out.println("Confirm password: " + pwd);
Thread.sleep(10000);
driver.manage().timeouts().implicitlyWait(100, TimeUnit.SECONDS);

Try following:
after clicking Submit button; you can check whether this element is present on your page or not : driver.findElement(By.xpath(".//*[#id='_id9']/table/tbody/tr[2]/td[1]/table[1]/tbody/tr[5]/td[2]/a"));
if it is that means new page was loaded as login was successful or else it was a bad login.
you can do so after clicking submit button try following:
UPDATE
List<WebElement> myElemnt = driver.findElements(By.xpath(".//*[#id='_id9']/table/tbody/tr[2]/td[1]/table[1]/tbody/tr[5]/td[2]/a"));
loginSuccessful(myElemnt);
// implementation of loginSuccessful() function:
public boolean loginSuccessful(WebElement element){
try{
element;
return true;
}
catch(Exception e){
System.out.println("Bad Login Information!!");
return false;
}
}
OLD
String beforeTitle = driver.getTitle();
//put your Click Submit Button code here
String afterTitle = driver.getTitle();
if(beforeTitle.equals(afterTitle)){
System.out.println("Bad Login Information!!");
}

Related

Selenium Chrome Driver Trouble Selecting or Inputting for Login

I am trying to setup a tool to monitor my Plex account. I am using Chrome Driver to try and login to my Plex account with an email and password. I cannot manage to locate the input fields no matter what I try, whether by ID, XPath etc. I have run a test with the Selenium Chrome Plugin and it manages to to find the element by ID but when running the following Java code I cannot get the driver to find the email and password fields. The extra code is to deal with the Cookies pop up and seems to work, at least it dismisses the pop up.
...
File file = new File("src/chromedriver88.exe");
System.setProperty("webdriver.chrome.driver", file.getAbsolutePath());
LOGGER.info("Got Chrome driver - " + file.exists());
ChromeOptions options = new ChromeOptions();
options.addArguments("no-sandbox");
driver.get("https://www.plex.tv/en-gb/sign-in/");
// Sort out the cookies pop up if it's there
boolean present;
try {
driver.findElement(By.xpath("/html/body/div[2]/div[3]/a[2]"));
present = true;
} catch (NoSuchElementException e) {
present = false;
}
if (present) {
driver.findElement(By.xpath("/html/body/div[2]/div[3]/a[2]")).click();
}
// Wait for log in button to exist
WebDriverWait wait = new WebDriverWait(driver, 30);
#SuppressWarnings("unused")
WebElement elementLogin = wait.until(ExpectedConditions.presenceOfElementLocated(By.id("email")));
// Send log in details
WebElement username = driver.findElement(By.id("email"));
username.sendKeys("...");
WebElement pwd = driver.findElement(By.id("password"));
pwd.sendKeys("...");
// Click log in
driver.findElement(By.xpath("//html/body/div[1]/div/div/div/div[1]/form/button")).click();
Your email and password input inside a frame:
<iframe src="..." id="fedauth-iFrame"
#document
You need switch it first, use .frameToBeAvailableAndSwitchToIt:
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.id("fedauth-iFrame")));
WebElement username = wait.until(ExpectedConditions.elementToBeClickable(By.id("email")));
username.sendKeys("email");
WebElement pwd = wait.until(ExpectedConditions.elementToBeClickable(By.id("password")));
pwd.sendKeys("password");

how to select the auto popup hotel names in a hotel booking site in Selenium

I am working on automating the following hotel booking site. I need to select the auto popup hotel name once I type the hotel in the first search box...I don't know how to do this.
I have navigated through the link and clicked Demo, then clicked the first link that appeared on the page.
I tried to click on the first search box and I need to enter a hotel from the auto popup list...I don't know how to do this because this has no PAC-item...
https://www.phptravels.net/home
public class Question1 {
WebDriver Driver = null;
WebDriverWait wait = null;
String url = "https://phptravels.com/demo/";
#BeforeTest
public void beforeTest() {
System.setProperty("webdriver.chrome.driver","src\\test\\resources\\drivers\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("excludeSwitches",Arrays.asList("disable-popup-blocking"));
options.addArguments("--disable-popup-blocking");
Driver = new ChromeDriver(options);
Driver.manage().window().maximize();
Driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
wait = new WebDriverWait(Driver, 25);
String winHandle = Driver.getWindowHandle();
//Driver.switchTo().window(winHandle);
//new WebDriverWait(Driver, 20).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.cssSelector("iframe[title='webpush-onsite']")));
//new WebDriverWait(Driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("button#deny.button.close"))).click();
}
#Test
public void f() {
Driver.get(url);
System.out.println("*****In the main page*****");
String xpathDemo = "//*[#id=\"mega-nav-navigation\"]/div/ul[1]/li[2]/a";
Driver.findElement(By.xpath(xpathDemo)).click();
String Title = "PHPTRAVELS | Travel Technology Partner";
/*try {
wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.xpath("//*[#id=\"PopupSignupForm_0\"]/div[2]/div[1]")));
Driver.findElement(By.xpath("//*[#id=\"PopupSignupForm_0\"]/div[2]/div[1]")).click();
} catch(Exception e) {
System.out.println("No popup..."+ e.getMessage());
}
*/
String username = Driver.findElement(By.xpath("//*[#id=\"Main\"]/section[2]/div/div/div[2]/div/div/div[2]/div[2]/div/div[3]/div[2]/div")).getAttribute("innerText");
username = username.substring(6) ;
String password = username.substring(30);
System.out.println("Username text :"+username + "\npassword is:"+password);
Driver.findElement(By.xpath("//*[#id=\"Main\"]/section[2]/div/div/div[2]/div/div/div[2]/div[2]/div/div[1]/div/a")).click();
utils.HelperFunctions2.switchToWindow(Driver, Title);
Driver.findElement(By.xpath("//*[#id=\"s2id_autogen16\"]")).click();
Driver.findElement(By.xpath("/html/body/div[7]/ul")).click();
}
#AfterTest
public void afterTest() {
Driver.quit();
}
}
Below xpath is result of 1st hotel, changing the index it will intreact with rest of the elements.
After filing text to the hotel text box.
give Thread.sleep(2000);
use below xpath. I hope it will work
(.//ul[#class='select2-results']/following::div[#class='select2-result-label'])[2]
I have already built bots, auto image pickers and more and I have never used the By.xpath method. Classname is much easier to use!
public void f(){
Driver.get(url);
String getInputFocusId = "select2-input";
Driver.findElement(By.className(getInputFocusId).click();
//now focused!
String text = Driver.findElement(By.className("select2-match").getText();
//text is the first default search match of the list.
}
There is also a more complicated way.
In Selenium you can sendKeys to an Element.
If the input element is focused the first match is also focused.
By clicking on Enter the focused match will be searched and displayed in the input element.
Finally you have to read the data from the input Element!
public void f(){
Driver.get(url);
String getInputFocusId = "select2-input";
WebElement element = Driver.findElement(By.className(getInputFocusId);
element.click();
//element.sendKeys(Key.DOWN);
element.sendKeys(Key.ENTER);
String text = element.getText();
//this is the text of the first search match
//if you want to get the second or third just repeat sending the DOWN key.
}
IMPORTANT: Make sure to run each line delayed (200ms is a good time). This helps you finding errors... For example in the Instagram Auth Process I delayed a lot of lines, and it finally worked!
I hope my answer helps you!!!

How to click on the element using Selenium Webdriver

I'm trying to click on a pop-up alert message on a UI with Selenium Webdriver.
The problem is, it is not clicking on accept or cancel even if I explicitly and implicitly wait. Is there any other alternative to clicking on a pop-up message. I tried to send key by Robot and press enter, but it did not work too.
click ok popup message function:
try {
WebDriverWait wait = new WebDriverWait(driver, 40);
wait.until(ExpectedConditions.alertIsPresent());
Alert alert = driver.switchTo().alert();
report.log(LogStatus.INFO, "Displayed Pop-up Window Alert Message -> " + alert.getText() + " for the Field -> " + fieldName);
System.out.println("Displayed Pop-up Window Alert Message -> " + alert.getText() + " for the Field -> " + fieldName);
alert.accept();
Thread.sleep(3000);
} catch (NoAlertPresentException ex) {
System.err.println("Error came while waiting for the alert popup. ");
report.log(LogStatus.INFO, "Alert pop up box is NOT populating when user clicks on: ");
}
this is what the html looks like for the popup:
<input type="submit" name="ctl00$ctl00$Content$ContentPlaceHolderMain$Continue" value="Continue..."
onclick="if(warnOnDelete('ctl00_ctl00_Content_ContentPlaceHolderMain_EditRadioOptions_1',"
+ "'Please confirm if you wish to delete.') == false) return false;"
id="ctl00_ctl00_Content_ContentPlaceHolderMain_Continue" style="width:100px;">
It has to be in IE, we are not allow to use anything except IE
Update: function for the confirm boxes
function warnOnDelete(deleteButtonID, msg) {
var deleteRadioButton = document.getElementById(deleteButtonID);
if (deleteRadioButton != null) {
if (deleteRadioButton.checked == true)
return confirm(msg);
}
return true;
}
Seems the element is not an Alert but an <input> element and to click() on the element you have to induce WebDriverWait for the elementToBeClickable() and you can use either of the following Locator Strategies:
cssSelector:
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("input[id$='_Content_ContentPlaceHolderMain_Continue'][value^='Continue'][name$='Continue']"))).click();
xpath:
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//input[contains(#id, '_Content_ContentPlaceHolderMain_Continue') and starts-with(#value, 'Continue')][contains(#name, 'Continue')]"))).click();

How to control the newly opened window that appears after a click in Selenium WebDriver?

I was just trying to automate the Gmail login process using Selenium WebDriver...After the email id is entered a new page opens to enter the password. How do I enter the password?
WebElement element= driver.findElement(By.xpath("//*[#id='ident']"));
element.sendKeys("THE EMAIL ID");
element.sendKeys(Keys.ENTER);
WebElement ele= driver.findElement(By.xpath("//*[#id='passd']"));
ele.sendKeys("THE PASSWORD");
ele.sendKeys(Keys.ENTER);
You have to switch the driver to current handler.
Please use below code to enter password.
WebElement element= driver.findElement(By.xpath("//*
[#id='ident']"));
element.sendKeys("THE EMAIL ID");
element.sendKeys(Keys.ENTER);
String mainWindowHandler = driver.getWindowHandle();
for(String winHandle : driver.getWindowHandles()) {
if (!mainWindowHandler.equals(winHandle)) {
driver.switchTo().window(winHandle);
}
}
WebElement ele = driver.findElement(By.xpath("//*[#id='passd']"));
ele.sendKeys("THE PASSWORD");
ele.sendKeys(Keys.ENTER);

How to check if button clicked, IF form is actually submitted Selenium / TestNG

I am new to java/selenium/testNG, I have an issue were I run 4 sets of data using the dataprovider, however, One set of data is incorrect just for the purpose of testing that the test works. I first check the button is displayed then clicked. I want to be able to check that the button was clicked and then check if the form was submitted IF the form was not submitted then print error. I am unsure on how to do this my code is below:
WebElement login = driver.findElement(By.id("dijit_form_Button_1_label"));
//If statement - will check if element is Displayed before clicking on login button.
if(login.isDisplayed()){
login.click();
//Main Event is logged If Passed
Reporter.log("Login Form Submitted | ");
logger1.info("Submit Button Clicked");
}else{
Reporter.log("Login Failed | ");
Assert.fail("Login Failed - Check Data | ");
//Main Event Log Fail
}
WebElement logout = driver.findElement(By.id("dijit_form_Button_0_label"));
if(logout.isDisplayed()){
logout.click();
Reporter.log("Logout Successful | ");
}else {
Reporter.log("Logout Failed");
Assert.fail("Logout Failed - Check Data | ");
}
The test displays a error message as "logout Failed" but it should display the first message "Login Failed" How do I get it to check if login and form was submitted successfully?
The reason it prints the second message is the code runs passed that point and selenium cant see the logout button displayed.
Any thoughts on were I am going wrong?
Try this:
private static By outButton = By.id("dijit_form_Button_0_label");
if(driver.findElements(outButton).size() > 0)
{
logout.click();
Reporter.log("Logout Successful | ");
}
after submitting the form, you should make the webdriver wait for some condition to be true.
something like that
int timeout = 30
WebDriverWait wait = new WebDriverWait(driver, timeout);
wait.until(new Function <WebDriver, Boolean>(){
//#Override
public Boolean apply(WebDriver driver) {
//if the login has been successful return true
//if not, return false
}
});

Categories

Resources