0

I am trying to get value of HREF attribute but always it says incorrect Xpath.

Html Code :

enter image description here

I am trying code :

     WebElement Link = driver.findElement(By.xpath("//table[contains(@class,'display')]/thead/tbody/tr/td/a"));
     System.out.println(Link.getAttribute("href"));

I tried many xpath but none of them worked.

8
  • 2
    1) should it not be: //table[contains(@class,'display')]/tbody/tr/td/a? 2) There might be other elements which match that expression, are you sure you've got the right element addressed? 3) Who says incorrect Xpath and how (i.e. any more error details)? 4) Please show use the code, where you try to get value from href attribute. Commented Jan 20, 2016 at 9:05
  • 1
    Post the HTML please. Commented Jan 20, 2016 at 9:08
  • I agree with the previous commenters, here is a summary of what they said: stackoverflow.com/help/mcve. Commented Jan 20, 2016 at 9:10
  • @DmytroPastovenskyi - I can not. But xpath given from Würgspaß worked for me. Commented Jan 20, 2016 at 9:46
  • Please note that Stackoverflow requires that a question includes all the necessary information about a problem as text (i.e. not in images). In this case, your question lacks the HTML source document. If you do not add it, it is likely that your question will be closed. Commented Jan 20, 2016 at 9:50

1 Answer 1

2

This should work:

 WebElement Link = driver.findElement(By.xpath("//table[contains(@class,'display')]/tbody/tr/td/a"));

Explanation: tbody is not nested in thead.

Note that a path expression like this can return a set of several nodes, in document order. The findElement method only returns the first result node. So: if the a element you are looking for is no longer the first one in this table, the path expression breaks.

If the the href is unique, something like this would be less error-prone:

 WebElement Link = driver.findElement(By.xpath("//table[contains(@class,'display')]//a[@href='/admin/client/product_overrides/edit/242625']"));
Sign up to request clarification or add additional context in comments.

3 Comments

How does the first expression depend on the order of rows? As I see it, you meant to say that the first expression depends on the implicit assumption that the first node in the result set will be the wanted one, since findElement only returns the first result.
@MathiasMüller Yes, that's what I meant. If the page code changes and some other a element happens to be the first one to appear in the table body, the test might fail. Feel free to edit the answer, to point it out.
Edited with your permission - and upvoted without your permission :-).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.