Java Selenium looping through website sendKeys combine strings together - java

I have a for loop that constantly loops back a website to fill out and submit a search box with the next string from a list.
For example, if the list contains [abcd, efgh, ijkl....], the first loop would send abcd, the second loop would send efgh and etc.
Currently the loop sends the first string correctly, but on every loop afterwards, the string sent is added to the previous string. So instead of efgh on the second loop, it is abcdefgh.
How do I clear the keys so that I can just send the individual string? Here's what I have right now:
for(String value : List){
driver.get(Link);
Actions actions = new Actions(driver);
WebElement input_field = driver.findElement(By.id("txtBoxSearch"));
actions.moveToElement(input_field);
actions.click();
actions.sendKeys(value);
actions.build().perform();
WebElement submit_key = driver.findElement(By.xpath("//button[contains(#title, 'Search')]"));
actions.moveToElement(submit_key);
actions.click();
actions.build().perform();
}

You need to clear the content of textbox before write value to it
for(String value : List){
driver.get(Link);
Actions actions = new Actions(driver);
WebElement input_field = driver.findElement(By.id("txtBoxSearch"));
input_field.clear();
actions.moveToElement(input_field);
actions.click();
actions.sendKeys(value);
actions.build().perform();
WebElement submit_key = driver.findElement(By.xpath("//button[contains(#title, 'Search')]"));
actions.moveToElement(submit_key);
actions.click();
actions.build().perform();
}

Here is the Answer to your Question:
Once you call click() method on the on the desired element through action class instance, next use the action class instance to clickAndHold, send CONTROL A and then send the new text DebanjanB to the form control to overwrite the previous text as follows:
for(String value : List){
driver.get(Link);
Actions actions = new Actions(driver);
WebElement input_field = driver.findElement(By.id("txtBoxSearch"));
actions.moveToElement(input_field);
actions.click();
actions.clickAndHold(input_field).sendKeys(Keys.chord(Keys.CONTROL, "a"), "DebanjanB").build().perform();
WebElement submit_key = driver.findElement(By.xpath("//button[contains(#title, 'Search')]"));
actions.moveToElement(submit_key);
actions.click();
actions.build().perform();
}
Let me know if this Answers your Question.

Related

Send text to the text-box of ClientName, when click on Addmore button creates new Textbox with same id and class-name

Dynamically created text-box on add button click with same id and class-name not able to send text second/third text-box.
List<WebElement> clientidtxt = driver.findElements(By.xpath("//label[contains(.,'Client ID')]/following::input[#id='CId']"));
for (WebElement webElement1 : clientidtxt)
{
if(!clientidtxt.isEmpty())
{
clientId.sendKeys(Keys.ENTER);
clientId.sendKeys(uuid);
System.out.println(webElement1.getText());
}
}
I have already send text to first text-box but not able to send to the second or third ....
Your code is kinda confusing.
You are looping through a list of web elements but inside you check to see if the list is empty... it can't be if you are looping through the list so that part can be removed.
You are using a foreach but you aren't actually using webElement1 but instead are referencing clientId which isn't declared in the code you posted.
I've updated the code with a best guess. Try this and see if it's what you are looking for.
List<WebElement> clientidtxt = driver.findElements(By.xpath("//label[contains(.,'Client ID')]/following::input[#id='CId']"));
for (WebElement webElement1 : clientidtxt)
{
webElement1.sendKeys(Keys.ENTER); // What's this for? Can this be removed?
webElement1.sendKeys(uuid);
System.out.println(webElement1.getText()); // if webElement1 is an INPUT, this needs to be webElement1.getAttribute("value") to return what the INPUT contains
}

Selenium WebDriver: Extracting strings in a search result using a loop

I'm trying to click on all the search results with a loop and get the title strings from each of the results. So it would click on a result try to extract the string.
String title = null;
List <WebElement> links = driver.findElements(By.className("thumbnail"));
ArrayList<String> tabs = new ArrayList<String> (driver.getWindowHandles());
for(int i=0; i<1; i++){
links = driver.findElements(By.className("thumbnail")); // this step is must, because whenever you go to other page all store WebElements in a list will wash out
links.get(i).click();
//it opens the search result in a new tab and gains focus on that tab
WebDriverWait wait = new WebDriverWait(driver, 10);
By addItem = By.xpath("//*[#id=\"HEADING\"]");
// get the "Add Item" element
WebElement element1 = wait.until(ExpectedConditions.presenceOfElementLocated(addItem));
wait.until(ExpectedConditions.stalenessOf(element1));
if(!driver.findElements(By.xpath("//*[#id=\"HEADING\"]")).isEmpty()) {
title = driver.findElement(By.xpath("//*[#id=\"HEADING\"]")).getText();
}
else {
System.out.println("Title is missing");
}
System.out.println(title);
driver.switchTo().window(tabs.get(0)); //Switching to first tab
}
The code is extracting the title on the first page rather than the page it clicked on. I'm also trying to extract other strings such as address, email, etc but i'm just testing this out. How do I fix this? Any help would be appreciated, thank you!
There were a few things that I changed.
I moved all your locators (and some other declarations) to the top and outside of the loop so they aren't redeclared inside the loop and so that they can be referenced by the .findElement() calls.
Since you are only using the current window handle, changed the variable type to String and just got the current window handle (instead of the collection of handles) so that you can switch back to the main tab at the end of the loop.
Moved the staleness check right after the click since that's where you need it and changed it to wait for the thumbnail that was just clicked.
Changed the XPath locator to use ID since that's all you were referencing. It's faster, shorter, and easier to read.
The second wait now waits for the collection of elements and then uses that collection to test for empty and get the text of the first in the collection.
By addItemLocator = By.id("HEADING");
By thumbnailsLocator = By.className("thumbnail");
List<WebElement> links = driver.findElements(thumbnailsLocator);
String originalTab = driver.getWindowHandle();
Set<String> tabs = driver.getWindowHandles();
WebDriverWait wait = new WebDriverWait(driver, 10);
for(int i = 0; i < links.size(); i++)
{
links = driver.findElements(thumbnailsLocator); // this step is must, because whenever you go to other page all store WebElements in a list will wash out
links.get(i).click();
// it opens the search result in a new tab and gains focus on that tab
// switch to the new window
for(String handle : driver.getWindowHandles()){
if (!handle.equals(originalTab))
{
driver.switchTo().window(handle);
break;
}
}
// get the "Add Item" element
List<WebElement> addItems = wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(addItemLocator));
if(!addItems.isEmpty())
{
System.out.println(addItems.get(0).getText());
}
else
{
System.out.println("Title is missing");
}
driver.close(); // close current tab
driver.switchTo().window(originalTab); // switch to original tab
}

How to use navigate back in for each loop?

I want to click on an element inside a list and go to different page. In this page I m taking a string. Then I go back and do the same for others. But after one iteration my code can't find the second element and shuts down the browser. Am I using the navigator wrong?
Here is my code:
public MainPage ControlSorting() {
List <WebElement> listItems=driver.findElement(RESULTCONT).findElements(MEDIA);
String[] strImdb = new String[listItems.size()];
int l = 0;
for (WebElement ele1 : listItems) {
ele1.click();
WebElement element = getElementBy(ABOUTIMDB);
String a= element.getAttribute("ng-genre-action");
String[] parts = a.split(",");
strImdb[l]=parts[1];
l++;
driver.navigate().back();
}
return this;
}
After going back you have to re identify the object. Please add the following code inside for loop at the first line of your code.
listItems=driver.findElement(RESULTCONT).findElements(MEDIA);
This should work. Please try and let me know.

Error while checking the clickable web element

I am facing problem while checking the clickable web element.
So i have to check the alphabetic series and some of the alphabet are clickable and some are not clickable.
i used for loop for it starting with xpath of alphabet 'A'
and going in loop till alphabet 'Z'.
but as soon as xpath of alphabet A is click & pass it goes to alphabet 'B'
which is not clickable and due to this whole script is getting fail.
here is the code
for(int j=3; j<=26;j++) {
String T1 =".//*[#id='twctvEl']/div/div/div[1]/ul/li[";
String T2 = "]/a";
String T12 = T1+j+T2;
chrome.findElement(By.xpath(T12)).click();
String alpha =chrome.findElement(By.xpath(T12)).getText();
System.out.println("checking the alphabet"+alpha);
}
Please advice here
NOTE: In the series of alpha bet from A-Z only B,Q,S,X,Y,Z are not clickable rest all are clickable.
You can add waits before element to become clickable:
for(int j=3; j<=26;j++)
{
String T1 =".//*[#id='twctvEl']/div/div/div[1]/ul/li[";
String T2 = "]/a";
String T12 = T1+j+T2;
WebElement el = chrome.findElement(By.xpath(T12));
WebDriverWait wait = new WebDriverWait(driver, timeout);
WebElement el= wait.until(ExpectedConditions.elementToBeClickable(element));
el.click();
String alpha =el.getText();
System.out.println("checking the alphabet"+alpha);
}
You can check if the element is visible and enabled before clicking on it
WebElement letter = chrome.findElement(By.xpath(T12));
if (letter.isDisplayed() && letter.isEnabled()) {
letter.click();
}
Well, it seems that when you click the element "A", it take you to another page or context and for this reason, during next iteration chrome driver is not able to find your Element "B" using xPath.

What is the difference between findElement(By) & findElementBy()?

WebElement p1 = (new FirefoxDriver()).findElement(By.xpath("//div[#class = 'site-title']")) ;
WebElement p2 = (new FirefoxDriver()).findElementByXPath("//div[#class = 'site-title']") ;
I m doing same thing: I select element by xpath, but in first line, I do it using findElement(By.xpath) and 2nd I use whole expression findElementByXpath.
and I still use same firefox driver object!
Is this because the By. is interface and accessed differently?
According to the source code of selenium java bindings, findElementByXPath() basically is just a shortcut to findElement(By.xpath, ...):
public WebElement findElementByXPath(String using) {
return findElement("xpath", using);
}
findElement() method -
Identify the one element (text field, label etc) from the web-page
WebElement p1 = (new FirefoxDriver()).findElement(By.xpath("//div[#class = 'site-title']")) ;
findElements() method -
Identify the multiple elements from webpage, like table rows and colums
List<WebElement> p1List = (new FirefoxDriver()).findElements(By.xpath("//div[#table='divTableData']")) ;

Categories

Resources