2

Trying to find link element of "a href". Snippet code:

<div id="contact-link">
    <a href="http://automationpractice.com/index.php?controller=contact" title="Contact Us">Contact us</a>
</div>

I managed doing it by:

  1. Driver.FindElement(By.XPath("//*[@title='Contact Us']")).Click();

2.Driver.FindElement(By.XPath("//a[@href='http://automationpractice.com/index.php?controller=contact']")).Click();

3.Driver.FindElement(By.XPath("//*[text()='Contact us']")).Click();

Could someone tell me how can I get by firstly getting parent div and then find what's inside that div (by going from the top to the bottom)

Ixi11
  • 219
  • 2
  • 14

2 Answers2

1

So basically, with xpath, you are looking to replicate the HTML structure. What you need is:

//div[@id='contact-link']/a

This is going to return the a href under the div. Assuming its just 1, thats the way to go. If you want to go a little further, try:

//div[@id='contact-link']/a[@title='Contact Us']
Anand
  • 1,899
  • 1
  • 13
  • 23
1

Although you have already accepted the answer , I would like to highlight some point about Xpath and cssSelector. You should always pick cssSelector over Xpath :

Here is cssSelector for your requirement:

div[id='contact-link']>a

Code :

Driver.FindElement(By.CssSelector("div[id='contact-link']>a")).Click();

For more about cssSelector : https://www.w3schools.com/cssref/css_selectors.asp For Difference between Xpath and cssSelector, you can read it from this SO post: Diff between Xpath and cssSelector

cruisepandey
  • 28,520
  • 6
  • 20
  • 38