如何查找iFrame元素

时间:2018-12-27 21:55:14

标签: java selenium xpath iframe css-selectors

我正在尝试找到iFrame Web元素,但是却显示“无此类元素异常”。

这是我尝试定位iFrame的方式:

@FindBy(id="iframe_uz04pghfaa")
public WebElement ifrmContactIframe;

public void SwitchToIframe() throws ParserConfigurationException, SAXException, IOException 
{       
    try 
    {
        ifrmContactIframe.isDisplayed();    //if the element is displayed it means that he exist
        driver.switchTo().frame(ifrmContactIframe);
    }
    catch (Exception e)
    {
        fail("Element does not exist"); 
    }
}

HTML快照: This is picture of the site code

3 个答案:

答案 0 :(得分:0)

要找到并切换到 iFrame ,您需要:

  • 诱导 WebDriverWait 以使所需的框架可用并切换到它。
  • 您可以使用以下解决方案:

    • 使用CSS_SELECTOR

      new WebDriverWait(driver, 10).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.cssSelector("iframe[id^='iframe_'][name^='iframe_'][src^='/crm/contact/details/']")));
      
    • 使用XPATH

      new WebDriverWait(driver, 10).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.xpath("//iframe[starts-with(@id,'iframe_') and starts-with(@name,'iframe_')][starts-with(@src, '/crm/contact/details/')]")));
      

PS :您可以在Ways to deal with #document under iframe

上找到相关的讨论

答案 1 :(得分:0)

很有可能是随机生成框架,请按照以下方法尝试:

    try 
        {
            List<WebElement> totalFrames = driver.findElements(By.cssSelector("*[id^='iframe_'"));
            System.out.println("Total FRMAES =" + totalFrames .size()); 
            ifrmContactIframe = totalFrames.get(0);

            ifrmContactIframe.isDisplayed();    //if the element is displayed it means that he exist
            driver.switchTo().frame(ifrmContactIframe);
        }
        catch (Exception e)
        {
            fail("Element does not exist"); 
        }

答案 2 :(得分:0)

  

很有可能是随机生成帧,在您的方法中,尝试   正在关注:

try 
    {
        List<WebElement> totalFrames = driver.findeElements(By.cssSelector("id^='iframe_'"));
        System.out.println("Total FRMAES =" + totalFrames .size()); 
        ifrmContactIframe = totalFrames.get(0);

        ifrmContactIframe.isDisplayed();    //if the element is displayed it means that he exist
        driver.switchTo().frame(ifrmContactIframe);
    }
    catch (Exception e)
    {
        fail("Element does not exist"); 
    }

@ kushal.8您说对了,我检查了一下,名字随机更改了, 我复制了您的代码,但仍然收到“元素不存在”的信息