selenium webdriver : sendkeys is not entirely send, it resets the text - java

I am doing a sendkeys on an element of input type but when I watch the navigator it writes for example "And", it erases, it writes "ré M", it erases, and it writes again "uzin" instead of just writting "André Muzin".
So my test is failed.
Here the code to find the element :
#FindBy(how = How.CSS, using = "input[data-automation-id='searchBox']")
public WebElement TB_MENTOR2;
Here the method which is calling it :
public void AddMentor(String functionality, String mentorName, String mentorType, String comment){
System.out.println(" ----- Going to the Mentor Page");
TB_SEARCH.sendKeys(functionality);
TB_SEARCH.sendKeys(Keys.ENTER);
TB_GOTO_ADDMENT.click();
TB_MENTOR1.click();
TB_MENTOR2.sendKeys(mentorName);
...
}
Do you have an idea ?

The webpage make a reset. And Selenium is typing really fast !
That's why I needed to wait 2s before sendKeys, to wait the reset.

Related

Selenium: ElementNotInteractableException: element not interactable when trying to access autoComplete text box

I am stuck with the WebElement which I am trying to access on the Webpage with the below code but still getting mentioned error. The Element allows to autocomplete the subjects and multiple subjects to be entered in the single text box.
WebElement Subjects = driver.findElement(By.xpath("//*[#id='subjectsContainer']"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", Subjects);
String subject1 = prop.getProperty("subject1");
String subject2 = prop.getProperty("subject2");
String subject3 = prop.getProperty("subject3");
Subjects.sendKeys(subject1);
Subjects.sendKeys(Keys.ENTER);
Subjects.sendKeys(subject2);
Subjects.sendKeys(Keys.ENTER);
Subjects.sendKeys(subject3);
Subjects.sendKeys(Keys.ENTER);
driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
WebElement accepts the multiple subjects to be entered by user which autocompletes
Selenium WebElement error
Looks like you need to add some delay or element visibility validation before you trying to send text to this element.
Additionally it's not recommended to use JavaScript click instead of WebDriver click unless you have no choice.
Please find below answer for my query as it is now working fine after putting Explict wait condition and locating correct webElement with tagname 'input'.
//Load the data from the Properties file
String subject1 = prop.getProperty("subject1");
String subject2 = prop.getProperty("subject2");
String subject3 = prop.getProperty("subject3");
//WebElement to capture the visibility condition
WebElement Subjects =driver.findElement(By.xpath("//*[#id='subjectsContainer']"));
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.elementToBeClickable(Subjects)).click();
WebElement Sub1 = driver.findElement(By.xpath("//input[#id='subjectsInput']"));
wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//input[#id='subjectsInput']")));
Sub1.sendKeys(subject1); //Send first Subject
Sub1.sendKeys(Keys.ENTER);
wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//input[#id='subjectsInput']")));
System.out.println("ENtered subject 1" + subject1);
Sub1.sendKeys(subject2); //Send second subject
Sub1.sendKeys(Keys.ENTER);
System.out.println("ENtered subject 2" + subject2);
wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//input[#id='subjectsInput']")));
Sub1.sendKeys(subject3); //Send thrid subject
Sub1.sendKeys(Keys.ENTER);
System.out.println("ENtered subject 3" + subject3);
A quick and dirty solution to many not interactable errors is simply this:
Thread.sleep(500);
I find this tactic to be extremely useful in quickly debugging problematic elements before implementing a more performant and elegant wait solution like you mentioned in your update.

Cannot get Past the Login Page

I can't get pass the login page. I'm correctly grabbing the input elements, populating them, and submitting but I still end up on the original page. I'm unsure where the exact issue is and I've tried ".submit, .click, and emulated a javascript ENTER to submit the credentials.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
//Create driver, javascript enabled
WebDriver driver = new HtmlUnitDriver(true);
driver.get("https://epicmafia.com/home");
//Get parent of login form
WebElement parent = driver.findElement(By.id("login_form"));
//Get both inputs of the login form
//First is name
//Second is password
ArrayList<WebElement> children = new ArrayList<WebElement>();
for(WebElement input : parent.findElements(By.cssSelector("input")))
children.add(input);
//Fill in name
children.get(0).sendKeys("USERNAME");
//Fill in password
children.get(1).sendKeys("PASSWORD");
//Wait for good measure
driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);
//Submit credentials
children.get(1).submit();
//Double check inputs are desired values
System.out.println("The username is: " + children.get(0).getAttribute("value"));
System.out.println("The password is: " + children.get(1).getAttribute("value"));
//Check if pass login page
System.out.println("End URL is: " + driver.getCurrentUrl());
driver.quit();
}
The login page is "https://epicmafia.com/home" while the next page upon successfully logging in would be "https://epicmafia.com/lobby".
edit: for reference: the third child element is the actual "Login" button that follows the first two(username and password).
The submit() should be performed on the <form> element
WebElement parent = driver.findElement(By.id("login_form"));
// fill the fields here
parent.submit();
You can try this code :
Since I do not have credentials, after clicking on log in button it'll show an error , you can provide the username and password in respective sendKeys("") command )
public class FFFF {
static WebDriver driver;
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "D:\\Automation\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://epicmafia.com/home");
driver.findElement(By.xpath("//form[#id='login_form']/descendant::input[#placeholder='username']")).sendKeys("username");
driver.findElement(By.xpath("//form[#id='login_form']/descendant::input[#placeholder='password']")).sendKeys("password");
driver.findElement(By.xpath("//form[#id='login_form']/descendant::input[#name='submit']")).click();
}
}
To send the character sequence to the username and password fields you need to induce WebDriverWait and click() on Login button you can use the following solution:
Code Block:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
# other lines of code
driver.get("https://epicmafia.com/home")
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input[name='user[username]']"))).send_keys("FF")
driver.find_element_by_css_selector("input[name='user[password]']").send_keys("FF")
driver.find_element_by_css_selector("input.red[value='Login']").click()
Browser Snapshot:
After looking at replies and messing around a bit the answer wasn't an error in grabbing the elements, populating them or even submitting. The problem was coming from the timeout not working, where I'd presumably thought it was.
I moved the driver to its own method kill switch so that the initial call has indefinite time to load before being manually killed off instead of automatically killed off as the code I originally posted.
Now my problem of logging in is fixed and I have to look into why the timeout isn't working. Thank you all for the help.

Calling href value in Selenium Webdriver

Could you please help me to call href value which is changing every time. Below is the code for your reference:
click here
Thanks.
As I understand from your comment, Test cases needed the href (link) attribute value. So code can be written by this way :
String strLinkHref = driver.findElement(By.linkText("click here")).getAttribute("href");
or
String strLinkHref = driver.findElement(By.xpath("//a[text()='click here']")).getAttribute("href");
Note : here you can store in String and print. It will get link dynamically every time.
If test case needed to open it, then you can use :
driver.get(strLinkHref);
If you require to move to TAB window, Please use below code :
String handle= driver.getWindowHandle();
System.out.println(handle);
// Click on the Button "New Message Window"
driver.findElement(By.name("New Message Window")).click();
// Store and Print the name of all the windows open
Set handles = driver.getWindowHandles();
System.out.println(handles);
// Pass a window handle to the other window
for (String handle1 : driver.getWindowHandles()) {
System.out.println(handle1);
driver.switchTo().window(handle1);
currentURL = driver.getCurrentUrl();
System.out.println(currentURL);
}
// Closing Pop Up window
driver.close();
Reference

How to return WebElement having particular CSS property using JavascriptExecutor?

I am working on a scenario where I need to find a WebElement based on its CSS property, like background-color.
I have created the JQuery to find the element as below and it finds the webelement correctly using firefox console.
$('.search-bar-submit').each(function() {
return $(this).css('background-color') == '#fdd922';
});
Hence, I wrote the code to find this WebElement, i.e. searchbox and then tried to click it.
driver.get("http://www.flipkart.com/");
driver.findElement(By.id("fk-top-search-box")).sendKeys("iphone");
String query ="$('.search-bar-submit').each(function() { "
+ "return $(this).css('background-color') == '#fdd922'; });";
WebElement searchbox = (WebElement) ((JavascriptExecutor)driver).executeScript(query);
searchbox.click();
When I run the program, it gives me Exception in thread "main" java.lang.NullPointerException on line searchbox.click();
Can anyone help me out find the searchbox using JavascriptExecutor and then click on it? Am I missing something silly here?
Any help is appreciated. Thanks in Advance.
WebElement searchbox = (WebElement)
((JavascriptExecutor)driver).executeScript(query);
The above code calls the function but doesn't do anything with the result, ie. it doesn't return it to the caller.
Add return in the script to return the webelement to the selenium script(webdriver)
return $('.search-bar-submit').each(function() {
return $(this).css('background-color') == '#fdd922';
});
The return type is List<WebElement>so typecast it to List if you typecast it to it will throw an ClassCastException as arraylist cannot be cast to a webelement
Code:
List<WebElement> searchbox = (List<WebElement>) ((JavascriptExecutor)driver).executeScript(query);
for(int i=0;i<searchbox.size();i++){
searchbox.get(i).click();
}
EDIT:
The code was not working in firefox because the firefox browser returns a json object of the webelement.Selenium replaced its uses of org.json with gson.So it is not able to understand the response recieved
Screenshot taken from chrome
Screenshot taken from firefox
Solution
We are using Jquery get function to retrieve the DOM Elements matched by the jquery object
$('.search-bar-submit').each(function() {
return $(this).css('background-color') == '#fdd922';
}).get(0);
Code
public class jquerytest
{
public static void main(String[] args) throws Exception {
WebDriver driver = new FirefoxDriver();
driver.get("https://www.flipkart.com");
driver.findElement(By.id("fk-top-search-box")).sendKeys("iphone");
String query ="return $('.search-bar-submit').each(function() { "
+ "return $(this).css('background-color') == '#fdd922'; }).get(0);";
Thread.sleep(5000);//wait till page loads replace thread.sleep by any waits
WebElement searchbox = (WebElement) ((JavascriptExecutor)driver).executeScript(query);
searchbox.click();
}
}
I have tested the above code on both chrome and firefox it works perfectly
Hope this helps you.Kindly get back if you have any queries
I ran the following code and it all works fine. Your jquery works as well (I love the little message they print to console in the dev view hahaha).
driver.get("http://www.flipkart.com/");
WebElement in = driver.findElement(By.id("fk-top-search-box"));
in.sendKeys("iphone");
WebElement thing = driver.findElement(By.className("fk-font-bold"));
thing.click();
I believe there's a problem with your executeScript and it should be as follows.
System.out.println(((JavascriptExecutor)driver).executeScript(query, driver));
Normally the format for my calling javascript is as follows, this would be to remove the windowed attribute so that a hyperlink would open in the same tab:
String Href = linkObject.getAttribute("href");//located the hyperlink for the documents
Href = Href.substring(0, Href.length()-10)+")";//I remove ",'windowed'" from the link to stop it opening in a new window and having to change the scripts focus
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("return arguments[0].href = \""+Href + "\"", linkObject););
But then you're getting JSON back and WebDriver can't understand that. See the following link for more information on that.
http://grokbase.com/t/gg/webdriver/12ckjcthg8/executing-javascript-that-returns-json-how-best-to-handle
Might I suggest this alternative, it gives the background-color in rgba format:
WebElement pain = driver.findElement(By.className("search-bar-submit");
pain.getCssValue("background-color");

Selenium autotest can't login with good credentials, but human can

This is my selenium java test.
I can login using my credentials on website, but selenium automatic test can not!
What could be the reason?
public void main() {
WebElement phone_field= firefox.findElement(By.xpath("//*[#id=\"login-form\"]/div[1]/span/input"));
WebElement password_field= firefox.findElement(By.xpath("//*[#id=\"login-form\"]/div[2]/span/input[#name=\"password\"]"));
Assert.assertNotNull(phone_field);
Assert.assertNotNull(password_field);
Assert.assertTrue(phone_field.isDisplayed());
Assert.assertTrue(password_field.isDisplayed());
phone_field.clear();
password_field.clear();
phone_field.sendKeys("5555555555");
password_field.sendKeys("222kek");
WebDriverWait wait = new WebDriverWait(firefox,3);
wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//div[#class='form-wrapper']")));
firefox.findElement(By.cssSelector("input.button.blue")).click();
String newUrl = firefox.getCurrentUrl();
System.out.println(newUrl);
Might it be the case that I need to make selenium wait for a bit,i.e. it presses on the blue login button too quickly?
so i found the answer myself! simply do this:
phone_field.clear() ;
phone_field.sendkeys("234234") ;
right after you clear you should 'type in' data!
this will not work:
field1.clear();
field2.clear() ;
....
field1.sendkeys() ;
field2.sendkeys() ;

Categories

Resources