Unable to find element in Selenium WebDriver By Na

2020-02-02 02:02发布

问题:

I am working with Selenium WebDriver and wrote a small code to find and element (i.e a button) and click on it. Here is the HTML code for the button:

<input type="submit" name="j_id0:j_id2:j_id3:j_id4:j_id7" value="New Master Health Program" onclick="AddLink()" class="btn">

Here is the C# code for the Test Case:

IWebElement newMasterHealthProgramsLink = driver.FindElement(By.Name("j_id0:j_id2:j_id3:j_id4:j_id7"));
newMasterHealthProgramsLink.Click();

I tried using XPath as well:

IWebElement newMasterHealthProgramsLink = driver.FindElement(By.XPath("//input[@id='j_id0:j_id2:j_id3:j_id4:j_id5']"));
newMasterHealthProgramsLink.Click();

I found a solution saying that you must not have implemented Wait for this. Page does not wait to load completely and tries to find the element. So I added wait command but nothing useful happened. Still getting the same error:

TestAutomation.Driver.Login:
OpenQA.Selenium.NoSuchElementException : The element could not be found

回答1:

Since your element is in an IFrame, you'll need to 'switch' to that IFrameusing the WebDriver API.

By default, Selenium will use the 'top' frame, and therefore any 'find element' queries will be directed to the most top frame, and ignore any child IFrames.

To solve this, 'switching' to the current IFrame directs Selenium to shove any requests to that frame instead.

driver.SwitchTo().Frame()

Note that you'll need a way of accessing the frame, either by it's ID, index (the top frame is 0, next frame down is 1, etc...) or name.

Another note is that any further requests will be directed to that IFrame, ignoring any others, which includes the top one...so if you need to access the top frame, you'll need to switch back:

driver.Switch().DefaultContent().