How to find the Xpath of <Td> tag from text which lie under <a> tag of that <td> in selenium c#



  • I have to find text on a page, which I did. Now I need to find the xpath of the

    <td>
    

    element containing that text so that I can use the

    <td>
    

    xpath to find other elements like the image button and the delete button.

    Image Description: This image contains one

    <Td>
    

    in which there is one

    <a>
    

    tag which contains text, i.e. Automation Testing, so first I have to find the text and then find the xpath of the

    <td>
    

    . The

    <a>
    

    tag contains an id attribute but this id changes dynamically according to the user input so I cannot find

    <a>
    

    tag with id.

    Html



  • This is actually easier than it sounds.

    First, unless you need to click the

    <a>
    

    link, you can retrieve the

    <td>
    

    element with the following:

    IWebElement element = driver.FindElement(By.Xpath("//td[contains(., 'Automation Testing')]"));
    

    Alternatively, if you need the

    <a>
    

    link, you can find the immediate parent (the

    <td>
    

    element with:

    IWebElement element = linkElement.FindElement(By.Xpath("./.."));
    

    From there the image buttons can be retrieved with linq-style queries (you will need to make sure you have using System.Linq; in your usings. element is the

    <td>
    

    element, which will make sure that your code doesn't retrieve anything outside your target table cell.

    List<IWebElement> elements = element.FindElements(By.TagName("img"));
    
    IWebElement addChild = elements.Where(el => el.GetAttribute("Title") == "Add Child");
    

    and so on.



Suggested Topics