Unable to sendKeys() into input text field - java

I intend to automate a simple form fill Junit test on the following website: https://newdesign.millionandup.com
The input textfield i am attempting to send keys to is identified with id=email and i have tried the following two methods:
1.
WebElement passInput = driver3.findElements(By.className("sidebar__item-text")).get(0); // this xPath does the trick
wait.until(ExpectedConditions.visibilityOfElementLocated(emailLocator));
passInput.click();
passInput.sendKeys("emailID");
Thread.sleep(3000); // only to see the result
WebElement em1 = driver3.findElement(emailLocator);
JavascriptExecutor jse = (JavascriptExecutor)driver3;
//driver3.findElement(emailLocator).sendKeys(emString);
Thread.sleep(1000);
jse.executeScript("arguments[0].click()", em1);
jse.executeScript("arguments[0].value='prisoner24601#gouvernement.fr';", em1);
if (em1.isSelected()) {
System.out.println("email typed");
} else {
System.out.println("unable to send keys, element not interactable");
}
To no avail in both cases, the textfield is still not interactable and i am unable to type the data into it.
EDIT: As suggested in the comments i have attempted a third way:
3.
WebElement element = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//input[#id='email']")));
System.out.println("email input located");
element.click();
System.out.println("email input clicked");
element.sendKeys(emString);
Element is actually located, but, as soon as the methods click() or sendKeys() are called, the execution stops after stating "element not interactable"

The xpath - //input[#id='email'] is matching 9 elements in the DOM. Its important to find unique locators - Link to refer
And the pop-up for Register opens on mouse movement. After mouse movement, will be able to view and interact with the pop-up elements.
Used below xpath to send keys to the element Email Address and it worked for me.
//form[#id='frmLeadModal']//input[#id='email']
Try like below once, it might work for you too.
driver.get("https://newdesign.millionandup.com/#initial");
WebDriverWait wait = new WebDriverWait(driver, 30);
Actions actions = new Actions(driver);
actions.moveByOffset(100, 100).perform();
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//form[#id='frmLeadModal']//input[#id='email']"))).sendKeys("example#email.com");

Related

if the next page xpath is displayed, click it and count the elements of the next page, and continue this as long as the next page exists

I have made a unique xpath for enabledNextPage. it is not found on the UI as long as the next page arrow is disabled. but on while loop it is giving me error that the element not found, which is correct that i wasn't found and it should not continue with the while loop. I used "try catch" and if the next page element is not present it still runs the while loop and gives me error on the next line which is to click it.
List<WebElement> rows = new ArrayList();
rows.addAll(driver.findElements(By.xpath("//*[#class='sortable-row']")));
while (schedulingModel.nextPageEnabled.isDisplayed())
{
nextPageEnabledXpath.click();
Thread.sleep(3000);
rows.addAll(driver.findElements(By.xpath("//*[#class='sortable-row']")));
}
I would rather have a different logic implemented by findElements, this will return me a list of next page arrow or link, if the size if >0 then it must have next page link, if not, well then no next page link.
List<WebElement> nextPageList = driver.findElements(By.xpath("xpath of next page arrow"));
if (nextPageList.size() > 0) {
System.out.println("Next page link is present");
// code to click on it, or count or whatever.
}
else {
System.out.println("Next page link is not present");
}
you can try with findElements instead using isDisplayed as it won't throw any exception if element is not present. it will be easy to share logic if you can share more details about your query like URL...
List<WebElement> rows = new ArrayList();
rows.addAll(driver.findElements(By.xpath("//*[#class='sortable-row']")));
while (driver.findElements(By.xpath("nextPageEnabled xpath value").size()>0)
{
nextPageEnabledXpath.click();
Thread.sleep(3000);
rows.addAll(driver.findElements(By.xpath("//*[#class='sortable-row']")));
}

Is there a way to search webelement on a main window first, if not found, then start searching inside iframes?

Requirement: Bydefault, search for webelement on main window, if found perform action else search for webelement inside iframes and perform required action
Selenium 3.141
'''
WebElement el = driver.findElement(By.xpath("//*[contains(text(),'here')]"));
boolean displayFlag = el.isDisplayed();
if(displayFlag == true)
{
sysout("element available in main window")
el.click();
}
else
{
for(int f=0;f<10;f++)
{
sysout("element available in frameset")
switchToFrame(frameName[f]);
el.click();
System.out.println("Webelement not displayed");
}
}
'''
My script is failing at first line itself. It is trying to find element in main window but element is actually available in iframe.
But the requirement is to search first in main window and then only navigate to iframes. How to handle such usecase?
Any suggestion would be helpful? Thank you.
Yes, you can write a loop to go through all the iframes if the element not present in the main window.
Java Implementation:
if (driver.findElements(By.xpath("xpath goes here").size()==0){
int size = driver.findElements(By.tagName("iframe")).size();
for(int iFrameCounter=0; iFrameCounter<=size; iFrameCounter++){
driver.switchTo().frame(iFrameCounter);
if (driver.findElements(By.xpath("xpath goes here").size()>0){
System.out.println("found the element in iframe:" + Integer.toString(iFrameCounter));
// perform the actions on element here
}
driver.switchTo().defaultContent();
}
}
Python Implementation
# switching to parent window - added this to make sure always we check on the parent window first
driver.switch_to.default_content()
# check if the elment present in the parent window
if (len(driver.finds_element_by_xpath("xpath goes here"))==0):
# get the number of iframes
iframes = driver.find_elements_by_tag_name("iframe")
# iterate through all iframes to find out which iframe the required element
for iFrameNumber in iframes:
# switching to iframe (based on counter)
driver.switch_to.frame(iFrameNumber+1)
# check if the element present in the iframe
if len(driver.finds_element_by_xpath("xpath goes here")) > 0:
print("found element in iframe :" + str(iFrameNumber+1))
# perform the operation here
driver.switch_to.default_content()

Unable to click or select the value which is displayed in dropdown

I am trying to implement some code using Selenium Webdriver using Java.
Basically, I have a website with a text box. Once user enter the first letter, based on that a value will be displayed(using AJAX). I need to select the particular value, which i mentioned in send keys .
WebElement fromCity = driver.findElement(By.id("pickUpLocation"));
fromCity.sendKeys("A Ma Temple / 媽閣");
Thread.sleep(2000);
WebElement ajaxContainer1 = driver.findElement(By.className("txt-box ng-touched ng-dirty ng-valid"));
WebElement ajaxHolder1 = ajaxContainer1.findElement(By.tagName("ul"));
List<WebElement> ajaxValues1 = ajaxHolder1.findElements(By.tagName("li"));
for (WebElement value1 : ajaxValues1) {
if (value1.getText().equals("A Ma Temple ")) {
((WebElement)ajaxValues1).click();
break;
}
}
After you send keys.your Ajax value should be retrieved in a box related to you keyword search.You need to get the complete box.and fetch each one as you have done in for loop .get the text and compare it with your expected text and click where this condition is true.
What is that line for before thread.sleep()
I think u can try selecting through index. It should be like this
List<WebElement> ajaxValues1 = ajaxHolder1.findElements(By.tagName("li"));
Select dropdown= new Select(ajaxValues1);
dropdown.selectByIndex(0);
dropdown.selectByIndex(1);
dropdown.selectByIndex(2);
0 represents the first element in the dropdown. Based on index number of that element, feed the corresponding number in selectByIndex(0)
Let me know if this helps. Thanks

Exception in thread "main" org.openqa.selenium.StaleElementReferenceException: stale element reference: element is not attached to the page document

I am getting element is not attached to the page document error for the above code. Moreover I want to know how to handle elements which 'appear' as a result of an action on the target page.
WebDriver driver = new ChromeDriver();
driver.get("https://www.irctc.co.in/eticketing/loginHome.jsf");
driver.manage().window().maximize();
driver.findElement(By.linkText("Sign up")).click();
//Verify whether the navigation is to the correct page
String title=driver.getTitle();
if (title.equals("IRCTC Next Generation eTicketing System")){
driver.findElement(By.id("userRegistrationForm:userName")).sendKeys("abcdef");
driver.findElement(By.linkText("Check Availability")).click();
WebElement text=driver.findElement(By.xpath(".//*[#id='userRegistrationForm:useravail']"));
boolean availability=text.isDisplayed();
try {if(availability==true){
System.out.println("The user id is available. Please enter other details to complete registration");
}}
catch (NoSuchElementException e){
System.out.println("The user id is not available. Please enter a different user ID.");
}
}
else
System.out.println("You are on a wrong page");
}
}
You need to create a custom wait to handle the element that will appear because of an action. So technically speaking, you are waiting for an expected condition to be true.
private void waitForElement(String element) {
WebDriverWait wait = new WebDriverWait(Driver, 10); // Wait for 10 seconds.
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(element)));
WebElement element = driver.findElement(By.xpath(element));
element.click(); // The element is now present and can now be clicked
}
In the above code you know the string / xpath of the element. You can pass it into this method and will wait for 10 seconds for the execpected conditon to become true. When it is true, the element can then be clicked.
Rather than catching an exception, the preferred way is to use .findElements() (plural) and then check for empty. If the collection is empty, the element doesn't exist on the page. If it exists, grab .get(0) and use it.
I added a few other optimizations to your code. I would do something more like this.
driver.get("http://toolsqa.com/automation-practice-table/");
driver.findElement(By.linkText("Sign up")).click();
// Verify whether the navigation is to the correct page
if (driver.getTitle().equals("IRCTC Next Generation eTicketing System"))
{
driver.findElement(By.id("userRegistrationForm:userName")).sendKeys("abcdef");
driver.findElement(By.linkText("Check Availability")).click();
List<WebElement> text = driver.findElements(By.id("userRegistrationForm:useravail"));
if (!text.isEmpty())
{
// element found
if (text.get(0).isDisplayed())
{
System.out.println("The user id is available. Please enter other details to complete registration");
}
}
else
{
// element NOT found
System.out.println("The user id is not available. Please enter a different user ID.");
}
}
else
{
System.out.println("You are on a wrong page");
}
If you perform some action and then need to wait for an element to appear, you can use WebDriverWait. An example is below that waits for a BUTTON to be visible and clicks it.
By buttonLocator = By.id("theButtonId");
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement button = wait.until(ExpectedConditions.visibilityOfElementLocated(buttonLocator));
button.click();
There are many other options under ExpectedConditions that you should check out in the docs linked.

Selenium is unable to locate any element in html page

I'm trying to make a small java app. that can log in to my university portal, I used Selenium in the following code:
//some import statements
public class Portal{
public Portal(){
File file = new File("C:/chromedriver.exe");
System.setProperty("webdriver.chrome.driver", file.getAbsolutePath());
HtmlUnitDriver driver = new HtmlUnitDriver();
String target = "http://portal.kfupm.edu.sa/cp/home/loginf";
driver.get(target);
ArrayList <WebElement> inputs = (ArrayList<WebElement>) driver.findElements(By.tagName("input"));
System.out.println(inputs.size());
for(WebElement input : inputs){
System.out.println(input.getAttribute("value") + " " + input.getAttribute("name"));
// to insure the link is displaying something
ChromeDriver driver1 = new ChromeDriver();
driver1.get(driver.getCurrentUrl());
}
public static void main(String [] args){
new Portal();
}
}
the problem is when I use this target (my university portal) I get inputs.size() = 0; although, I'm sure there are elements with (input) tagName. Also I get the same resulst whatever was the method of (By) class I used.
However, when I change the target to any link (for example: "http://www.google.com" or "http://www.facebook.com" , I get elements in the inputs ArrayList (all elements of tagName (input) that are in the target html page). Can any body please tell me what is the problem and how can I solve it? thanks in advance..
The reason that you find zero elements with tag input is that all the elements lie inside a frame tag. Selenium is able to see to current window and all the elements that are defined inside frame tag (i.e. are inside a frameset) are invisile to it.
To see the element you will need to switch frame first, So that selenium has control inside the target frame and not in the outer window. Try this
driver.swtichTo().frame(0); // this will move selenium control inside first frame

Categories