简体   繁体   中英

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?

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));

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"));

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM