How to Send Text to Text Box which have same xpath - selenium

In Selenium Webdriver we have three Text boxes. All the text boxes have the same Id, and I want to send some text in the second text box.
This is my code:
Driver.findElements(By.xpath("//*[#id='testInstanceScan']"));
Could anyone please help how to handle Text boxes which have same Id ?
Currently i m using below code which always send same text for all the three text boxes.
List<WebElement> textfield1 = Driver.findElements(By.xpath("//*[#id='testInstanceScan']"));
for(int i=0; i<textfield1.size();i++){
WebElement local_textfield1=textfield1.get(i);
String value1=local_textfield1.getAttribute("placeholder");
if(value1.equalsIgnoreCase(""))
{
local_textfield1.sendKeys("Amarendra Singh");
}
}

There are two ways to get the second textbox.
Method 1: using find elements
List<WebElement> textfields = Driver.findElements(By.xpath("//*[#id='testInstanceScan']"));
textfields.get(1).sendKeys("Amarendra Singh");
Method 2: using xpath
WebElement textfield2 = Driver.findElements(By.xpath("(//*[#id='testInstanceScan'])[2]"));
textfield2.sendKeys("Amarendra Singh");

You can use an array like trick to access each element matching the XPath
WebElement textField1 = driver.findElements(By.xpath("(//*[#id='testInstanceScan'])[1]"));
WebElement textField2 = driver.findElements(By.xpath("(//*[#id='testInstanceScan'])[2]"));

The quickest and easiest way I know to do this is to use an XPath to specify the expected ID and placeholder = "" and then specify the index of the element you want.
Given an HTML example of
<html>
<div id="testInstanceScan" placeholder="">e1</div>
<div id="testInstanceScan" placeholder="">e2</div>
<div id="testInstanceScan" placeholder="">e3</div>
</html>
The code below works
List<WebElement> searchBox = driver.findElements(By.xpath("//div[#id='testInstanceScan'][#placeholder='']"));
System.out.println(searchBox.get(1).getText());
and returns
e2
which is the element that contains the desired ID, empty placeholder attribute value, and is the second element. This form of XPath can be tailored to a lot of different situations to get the desired element in a single pass instead of looping or filtering the collection.
In your case, your final code would look like
List<WebElement> textfields = driver.findElements(By.xpath("//input[#id='testInstanceScan'][#placeholder='']"));
textfields.get(1).sendKeys("Amarendra Singh");
If that still doesn't work, you may need a wait.
By locator = By.xpath("//input[#id='testInstanceScan'][#placeholder='']");
List<WebElement> textfields = new WebDriverWait(driver, 10).until(ExpectedConditions.visibilityOfAllElementsLocatedBy(locator));
textfields.get(1).sendKeys("Amarendra Singh");

I don't know exactly what is yoyr question but what i understand you want to perform operation on textbox which have same xpaths
This is a sample Html which I used for example
<html>
<div id="test" placeholder="">element1</div>
<div id="test" placeholder="">element2</div>
<div id="test" placeholder="">element3</div>
<div id="test" placeholder="">element4</div>
</html>
First use findElements() to extract all elements and then use if loop to select one and perform operation This is my code
WebDriver driver=new FirefoxDriver();
driver.get("URL");
List<WebElement> allElements=driver.findElements(By.xpath("//div[#id='test']"));
for (WebElement tempElement : allElements) {
if(tempElement.getText().equalsIgnoreCase("element2"))
{
System.out.println(tempElement.getText()); // you can perform your operations
}
}

Related

How to construct an XPath which remove text from <br> tag?

I am trying to fetch text before the <br> tag using XPath & Java. I tried multiple solutions, but had no luck yet.
//div[#class="help-block"]/p[count(preceding-sibling::br) < 1]
This is my HTML code:
<div class="help-block">
<p>
This is sample text
<br>
Text after a breakpoint
</p>
</div>
Expected outcome: This is sample text.
Actual outcome: This is sample text Text after a breakpoint
To get the This is sample text Induce WebDiverWait And visibilityOfElementLocated() And get the element.
Induce JavascriptExecutor And get the textContent of firstChild
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element=wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[#class='help-block']/p")));
JavascriptExecutor js = (JavascriptExecutor) driver;
System.out.println(js.executeScript("return arguments[0].firstChild.textContent;",element));
I think you can just run this:
driver.find_element_by_xpath("//p[br]").text
This will get the <p> element, but the query also checks to make sure that <p> contains a <br> element inside it. So you are just getting the <p>, and .text should get the text from the <p>.
Your expression was close. But you didn't take into account that p is only one element and you want subnodes of p. So change your expression to the following (also escaping the < char)
//div[#class="help-block"]/p/node()[count(preceding-sibling::br) < 1]
It's output is:
This is sample text

How to write selenium code for autocomplete text box withe list selection

I'm trying to write Selenium code for below HTML source code..
This field is the auto populated field for input selection
<input id="ctl00_ContentPlaceHolder1_txtBranch" class="textbox_service ui-autocomplete-input" name="ctl00$ContentPlaceHolder1$txtBranch" style="width: 200px;" onblur="return branch();" onchange="return CheckBranchName();" tabindex="6" autocomplete="off" type="text"/>
Any one can help me out to write the code?
Web element screen shot attached.
Thanks in advance.
This is the best I could do with the information you provided. If you could show the HTML for what the autocomplete list looks like that would be great. You didn't specify any language so I'll assume it's Java.
WebElement field = driver.findElement(By.id("ctl00_ContentPlaceHolder1_txtBranch"));
field.click();
field.sendKeys(Keys.SPACE);
List<WebElement> items = driver.findElements(By.tagName("li");
for (int i=0; i<items.size();i++) {
WebElement elementYouWantToClick = items.get(i);
String x = elementYouWantToClick.getText();
if(x.contains("TextThatIsInYourElementYouWantToChoose")){
elementYouWantToClick.click();
}
Best I could do for now with such limited information.
As per the HTML to click(select) the Auto Complete text, you can use the following line of code :
new WebDriverWait(driver, 10).until(ExpectedConditions.elementToBeClickable(By.xpath("//input[#class='textbox_service ui-autocomplete-input' and contains(#id,'_ContentPlaceHolder') and contains(#name,'txtBranch')]"))).click();

How to get the span class text using selenium webdriver

I have a span as below:
<div class="ag-cell-label">
<span class="glyphicon glyphicon-asterisk" title="This is a draft row. It can only be seen by you. "/>
</div>
I want to get the text "glyphicon glyphicon-asterisk". How can I do it.
The validation of the test case is to check weather asterisk is not present after clicking on save button.
Assuming you are using Java, You should try as below :-
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement el = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[#class='ag-cell-label']/span")));
String class = el.getAttribute("class");
Hope it will help you...:)
This is a simple case of:
Locate the WebElement using a suitable locator strategy (Class, CSS, XPath etc) and assign it to a new WebElement object.
Use the .getAttribute(String arg) method with an argument of "class" to retrieve the required class value from the WebElement object instantiated in the first step and assign it to a new String object.
Use the .contains(String arg) method with an argument of "asterisk" to determine whether the "class" attribute retrieved in the second step contains the text "asterisk".

Using Selenium to select text

Want to select the text "This is for testing selector" from below HTML code.
<div class="breadcrumb">
<a title=" Home" href="http://www.google.com/"> Home</a>
<span class="arrow">»</span>
<a title="abc" href="http://www.google.com/">test1</a>
<span class="arrow">»</span><a title="xyz" href="http://www.google.com/">test2</a>
<span class="arrow">»</span>
This is for testing selector
</div>
I'm not sure if there an easy way out for this or not. It turned out to be more difficult than I thought. Below mentioned code is tested locally and giving correct output for me ;)
String MyString= driver.findElement(By.xpath("//div[#class='breadcrumb']")).getText();
//get all child nodes of div parent class
List<WebElement> ele= driver.findElements(By.xpath("//div[#class='breadcrumb']/child::*"));
for(WebElement i:ele) {
//substracing a text of child node from parent node text
MyString= MyString.substring(i.getText().length(), MyString.length());
//removing white spaces
MyString=MyString.trim();
}
System.out.println(MyString);
Let me know if it works for you or not!
Try with this example :
driver.get("http://www.google.com/");
WebElement text =
findElement(By.className("breadcrumb")).find("span").get(1);
Actions select = new Actions(driver);
select.doubleClick(text).build().perform();
I suggest also that you copy the xpath for the text you need and put it here to have the exact xpath
You cannot select text inside an element using xpath.
Xpath can only help you select XML elements, or in this case, HTML elements.
Typically, text should be encased in a span tag, however, in your case, it isn't.
What you could do, however, is select the div element encasing the text. Try this xpath :
(//div[#class='breadcrumb']/span)[3]/following-sibling::text()
You could try Abhijeet's Answer if you just want to get the text inside. As an added check, check if the string obtained from using getText() on root element contains the string obtained from using getText() on the child elements.

Selenium clicking a sub menu

I am Really stuck for the past two days here. I am trying to click sub menu and when I try to click sub menu I get an errors as like the following
Element not found for the sub menu.
I have tried below code
WebElement element = driver.findElement(By.id("x-menu-el-P46915788081933044__folderbrowser_PJL"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", element);
HTML Code
<li id="x-menu-el-P46915788081933044__folderbrowser_PJL" class="x-menu-list-item">
<a id="P46915788081933044__folderbrowser_PJL" class="x-menu-item" href="javascript:var abc = doNothing()" unselectable="on" hidefocus="true">
<img id="ext-gen926" class="x-menu-item-icon " src="netmarkets/images/import.gif">
<span id="ext-gen927" class="x-menu-item-text">Upload Documents from Compressed File</span>
Instead of using the ID you should probably use the class name.
WebElement element = driver.findElement(By.ClassName("x-menu-list-item"));
or you could try using the css selector
WebElement element = driver.findElement(By.cssSelector("li[class='x-menu-list-item']"));
Since the above return multiple items you could just use to return the exact element that you need:
WebElement element = driver.findElement(By.linkText("Upload Documents from Compressed File"));
1st click on the menu and then try the following statement -
driver.findElement(By.xpath("//li[#class='x-menu-list-item']//span[contains(text(),'Upload Documents from Compressed')])).click();
or directly try this -
driver.findElement(By.xpath("//span[contains(text(),'Upload Documents from Compressed')])).click();
I guess mostly the error is due to the span name spaces in between words, if the above dont work, pls attach a screenshot or give some details of the html code, so we can try more options, all d best.