0

I have the following HTML code:

<td class="gnb_menu" id="MAIN_04" name="MAIN_04" style="width:100px;text-align:center;">
  <span style="cursor:pointer;"  onclick="javascript:movePage('MAIN_04','/basis/menuServlet.do?method=getMenuUrl','body','Y')">
    <nobr>Business</nobr>
  </span>
</td>

I am trying to get the XPath of the span tag. I am using Selenium and have tried this:

cd.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);
var d = cd.FindElementByXPath("//td[@id='MAIN_04']/span[@style='cursor:pointer;']");
d.Click();

But keep running into the error: "OpenQA.Selenium.NoSuchElementException has been thrown" because it is unable to locate the element/no such element.

I have tried many different XPath (//*[@id='MAIN_04']/span),(//td[@id='MAIN_04']/span), etc. but still cannot get this right. I even tried to take out the implicit wait because I thought it was a timeout error... I don't know.

PLEASE HELP I am new to this and I'm so confused. Thank you!

Amy Shin
  • 13
  • 6

1 Answers1

0

After two days of researching this tiny error, I figured it out!

The code was inside a frame tag. I was under the impression that it only matters if the code is inside an iframe tag but I was wrong. This is my revised working code:

// Found the frame using its XPath (cd is my Chrome Driver)
IWebElement frame = cd.FindElement(By.XPath("/html/frameset/frame[2]"));
cd.SwitchTo().Frame(frame);
// Found the XPath of the span tag where my error was occurring 
IWebElement d = cd.FindElement(By.XPath("//td[@id='MAIN_04']/span"));
d.Click();

The HTML code was:

<frame name="menu" src="/basis/common/topMenu.jsp" scrolling="no" marginwidth="0" noresize="" marginheight="0">
...
...
  <td class="gnb_menu" id="MAIN_04" name="MAIN_04" style="width:100px;text-align:center;">
    <span style="cursor:pointer;" onclick="javascript:movePage('MAIN_04','/basis/menuServlet.do?method=getMenuUrl','body','Y')">
      <nobr>Business</nobr>
  </span>
</td>

In my case, I do not need to switch back to my default frame/content, but in case you do:

cd.SwitchTo().DefaultContent();

Got this with the help of @Andersson and iFrame Question! Thanks guys :)

Amy Shin
  • 13
  • 6
  • Don't use that XPath. Any locator that starts from the HTML tag or contains more than just a few levels of depth are fragile (likely to break with minor HTML changes). Instead reference the frame using the name attribute, 'menu'. Now it doesn't matter where in the DOM the frame is, your locator will find it. See [the docs](https://seleniumhq.github.io/selenium/docs/api/dotnet/?topic=html/M_OpenQA_Selenium_ITargetLocator_Frame_2.htm) – JeffC Oct 03 '18 at 17:10