Could not find element in Selenium WebDriver By name and XPath

I am working with Selenium WebDriver and wrote a little code to find and an element (like 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 also tried using XPath:

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

      

I found a solution that said you shouldn't implement Wait for this. The page does not wait for the full load and tries to find the item. So I added a wait command, but nothing useful happened. The error still occurs:

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

      

+3


source to share


1 answer


Since your element is in an IFrame, you need to "switch" to that IFrame using the WebDriver API.

By default, Selenium will use the "top" frame, and therefore any "find element" requests will go to the topmost frame and ignore any child IFrames.

To solve this problem, "switching" to the current IFrame directs Selenium to push any requests to that frame.

driver.SwitchTo().Frame()



Note that you need a way to access the frame: either its ID, index (top frame is 0, next frame down is 1, etc.), or a name.

One more note: any further requests will be directed to this IFrame, ignoring any others, including the top one ... so if you need to access the top frame, you'll need to go back:

driver.Switch().DefaultContent()

...

+3


source







All Articles