Search code examples
seleniumiframeselenium-webdriver

WebDriver - How to locate iframe without id


I'm trying to switch to an iframe in order to locate an element, but I'm unable to locate the iframe since it has no id or name

<div id="eyein-modal" style="display: block; position: fixed; width: 100%; height: 100%; top: 0px; left: 0px; bottom: 0px; right: 0px; z-index: 90000000; background-color: rgba(0, 0, 0, 0.6); overflow: auto; opacity: 1;">
<iframe style="display: block; width:90%; height:90%; border: 0px; margin: 2.5% auto; z-index: 90000000; overflow: hidden;" scrolling="no" src="about:blank">
<html>
   <head>
   <body class="">
      <div id="modal">
      <div id="modal-header">
      <div id="header-logo">
      <div id="title-container" class="">
      <a id="view-event" class="button" target="_blank" href="http://www.link.com">view event</a>
      <div id="close-modal" class="close-dark"></div>

close-modal is the element I need eventually


Solution

  • Aside from providing frame name or id, you can switch to the frame by index (zero-based):

    Select a frame by its (zero-based) index. That is, if a page has three frames, the first frame would be at index "0", the second at index "1" and the third at index "2". Once the frame has been selected, all subsequent calls on the WebDriver interface are made to that frame.

    driver.switchTo().frame(0);  // assuming this is the first frame on the page
    

    Or, you can make a WebElement instance by locating the iframe, for example, by CSS selector:

    WebElement frame = driver.findElement(By.cssSelector("div#eyein-modal iframe"));
    driver.switchTo().frame(frame);
    

    See also: