MattHodson
MattHodson

Reputation: 786

Getting <a> tag from parent element with Selenium

I'm trying to get the value of the <a> tag in this HTML through Selenium Chromedriver.

 <div class="_4mcc _3qn7 _61-0 _2fyi _3qnf">
 <i class="_3um9 img sp_XObDbAMxJiG sx_7127ff" alt=""></i>
 <a class="_6dvq" target="_blank" href="https://example.com/hello" rel="nofollow noopener" data-lynx-mode="hover">example.com/</a>
 </div>

I'm wanting to find example.com

Rules: I cannot use IDor css selectors because the HTML / CSS often changes. The only class which doesn't change is sp_XObDbAMxJiG, so I'm having to use this, and get the parent.

My code, which isn't working:

  var cssClass = driver.FindElement(By.ClassName("sp_XObDbAMxJiG"));
  var cssClassParent = cssClass.GetParent();
  var getA = cssClassParent.FindElement(By.CssSelector("a")); 
  var data = getA.GetAttribute("href");

and my GetParent() function:

public static class MyExtensions
{
    public static IWebElement GetParent(this IWebElement node)
    {
        return node.FindElement(By.XPath(".."));
    }
}

The following code errors at the getA stage, with:

{"no such element: Unable to locate element: {\"method\":\"css selector\",\"selector\":\"a\"}\n (Session info: headless chrome=81.0.4044.138)"}

But an <a> tag is definitely within this area on said page.

For more clarity, this is the page I'm attempting to get the URL from here: https://www.facebook.com/momandpopmusic (I'm attempting to extract their business URL - purely an example page, and purely for educational purposes).

Upvotes: 0

Views: 299

Answers (1)

Dazed
Dazed

Reputation: 1551

Since "sp_XObDbAMxJiG" remains constant, you can try this:

var url = driver.FindElement(By.XPath("//i[contains(@class, 'sp_XObDbAMxJiG')]/following-sibling::a")).GetAttribute("href");

Upvotes: 2

Related Questions