1

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

  • 1
    Have you tried using CroPath? Mark Smith. – Sperk Aug 13 at 7:49
1

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.

0

Please use the below code, hope it helps.

//to find the image with title = Add Child

IWebElement element = 
driver.FindElement(By.xpath("//*[contains(text(),'Automation')]/following-sibling::* 
[1]");

//to find the image button with title = Delete

IWebElement element = 
driver.FindElement(By.xpath("//*[contains(text(),'Automation')]/following-sibling::* 
[3]");
0

Try with absolute Xpath this is an example: /td[a[@href='url-a']]/following-sibling::td[1]/a/text()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.