【问题标题】:How to find an iFrame element如何找到 iFrame 元素
【发布时间】:2019-05-25 20:22:42
【问题描述】:

我正在尝试查找 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 快照:

【问题讨论】:

  • 欢迎来到 Stack Overflow!请阅读为什么a screenshot of code is a bad idea。粘贴代码并正确格式化。
  • 您是否检查过 ID 是否在每次刷新时发生变化? .isDisplayed() 不仅仅检查元素是否存在......它检查它是否可见。你不应该需要那个检查,因为如果它不存在,下一行无论如何都会失败。

标签: java selenium xpath iframe css-selectors


【解决方案1】:

要定位并切换到 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的相关讨论

【讨论】:

  • @Liorp FrameIdFrameName 是动态生成的。 implicitlyWait 是不够的。您需要 WebDriverWait
  • 我尝试了等待选项,但它仍然无法识别 iFrame:' new WebDriverWait(driver, 10).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.id("iframe_uz04pghfaa")));'
  • @Liorp 你在哪里找到 By.id("iframe_uz04pghfaa") 在这个答案中?
  • 我以为我在其中一个答案中看到了它,但没关系,我将其更改为 'By.name' 但它仍然找不到 iFrame: 'new WebDriverWait(driver, 10 ).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.name("iframe_uz04pghfaa"))); ' 顺便问一下,按名称搜索和按 id 搜索有什么区别?
  • @Liorp 你在哪里找到 By.name("iframe_uz04pghfaa") 在这个答案中?
【解决方案2】:

您的帧很可能是随机生成的,在您的方法中,请尝试以下操作:

    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"); 
        }

【讨论】:

    猜你喜欢
    • 2021-10-13
    • 2021-12-30
    • 1970-01-01
    • 2020-08-02
    • 2021-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-07
    相关资源
    最近更新 更多