Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find an element by text and get xpath - selenium webdriver junit

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);
 }
}
like image 892
Nandini Joshi Avatar asked Aug 29 '13 12:08

Nandini Joshi


People also ask

Can XPath locate element using text?

text(): A built-in method in Selenium WebDriver that is used with XPath locator to locate an element based on its exact text value.

How do I search for text in XPath?

So, inorder to find the Text all you need to do is: driver. findElement(By. xpath("//*[contains(text(),'the text you are searching for')]"));

How do you getText from a text box in Selenium?

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.


1 Answers

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;
}
like image 79
Scott Izu Avatar answered Oct 21 '22 08:10

Scott Izu