silhouette hustler
silhouette hustler

Reputation: 1763

Locate an HTML element inside of the <iframe> by using Xpath (selenium c#)

I am trying to find this element by partial class, the HTML code is as following :

<a class="follow-button profile" href="https://twitter.com/123" 
role="button" data-scribe="component:followbutton" title="Follow 123 
on Twitter"><i class="ic-button-bird"></i>Follow</a>

The method I used is as following:

var element = Driver.FindElement(By.XPath("//a[contains(@class, 'follow-button profile')]"));

Any ideas what might be the reason for not being able to locate the element?

Upvotes: 0

Views: 3319

Answers (3)

Richard
Richard

Reputation: 9019

NoSuchElement exception generally has one of the following causes:

  1. Your element is inside a <frame> or <iframe>. Examine your HTML for those.

    • If this is the case, you can use SwitchTo().Frame()
    • Frame() accepts 3 arguments
      • An IWebElement
        • IWebElement frameElement = driver.FindElement(By.Tag("frame"));
        • driver.SwitchTo().Frame(frameElement);
      • name of <frame name="MyFrame"> or <iframe>
        • driver.SwitchTo().Frame("MyFrame");
      • Index of the <frame> or <iframe>, starting from 0
        • SwitchTo().Frame(0)
    • After you finish in the <frame> context, you will need to switch back to the correct context
      • driver.SwitchTo().DefaultContent();
  2. Your element is loading on the page after Selenium thinks your page has finished loading

    • If this is the case, you can use Wait to tell Selenium to pause until the element finishes loading on the page.
    public WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(2));
    wait.Until(driver => driver.FindElement(ByLocator));

Upvotes: 1

Vishal Jagtap
Vishal Jagtap

Reputation: 896

Might be class value is changing in your case at run time. You can try manually and check this.

Upvotes: 0

Amey
Amey

Reputation: 8548

There are multiple classes in the element that you are trying to locate. The correct way to use xpath in that case is as follows:

var element = Driver.FindElement(By.XPath("//a[contains(@class, 'follow-button ') and contains(@class, 'profile')]"));

You could also use css

var element = Driver.FindElement(By.CssSelector(".follow-button.profile"));

Upvotes: 0

Related Questions