I have a table with 9 rows and 6 columns in my webpage. I want to search for a text "MakeGoodDisabled-Programwise_09_44_38_461(n)" and get the xpath of the cell. I have used the following but it fails because it is not able to find the text on the page. Can you please help? I am using Selenium Webdriver Junit to code this.
List < WebElement > links = driver.findElements(By.tagName("td"));
Iterator < WebElement > itr = links.iterator();
while (itr.hasNext()) {
String test = itr.next().getText();
if (test.equals("MakeGoodDisabled-Programwise_09_44_38_461(n)")) {
String xpath = driver.findElement(By.name(test)).getAttribute("xpath");
System.out.println(xpath);
}
}
text(): A built-in method in Selenium WebDriver that is used with XPath locator to locate an element based on its exact text value.
So, inorder to find the Text all you need to do is: driver. findElement(By. xpath("//*[contains(text(),'the text you are searching for')]"));
We can get the entered text from a textbox in Selenium webdriver. To obtain the value attribute of an element in the html document, we have to use the getAttribute() method. Then the value is passed as a parameter to the method. Let us consider a textbox where we entered some text and then want to get the entered text.
You can also use this to crawl up and generate the xpath:
Call the method below with
generateXPATH(element, "");
The output will be something like:
/html[1]/body[1]/div[5]/div[1]/div[2]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/form[1]/div[2]/div[1]/input[2]
METHOD
private String generateXPATH(WebElement childElement, String current) {
String childTag = childElement.getTagName();
if(childTag.equals("html")) {
return "/html[1]"+current;
}
WebElement parentElement = childElement.findElement(By.xpath(".."));
List<WebElement> childrenElements = parentElement.findElements(By.xpath("*"));
int count = 0;
for(int i=0;i<childrenElements.size(); i++) {
WebElement childrenElement = childrenElements.get(i);
String childrenElementTag = childrenElement.getTagName();
if(childTag.equals(childrenElementTag)) {
count++;
}
if(childElement.equals(childrenElement)) {
return generateXPATH(parentElement, "/" + childTag + "[" + count + "]"+current);
}
}
return null;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With