【问题标题】:webdriver.io: Find elements within an iframewebdriver.io:在 iframe 中查找元素
【发布时间】:2021-12-24 19:34:43
【问题描述】:

我正在尝试访问网页上 iframe 中的元素。

目标是切换到此 iframe 上下文,然后单击此 iframe 中的元素。这些元素在 iframe 之外是不可见的,但是当我切换到这个 iframe 时,我仍然看不到这些元素。

使用浏览器中的开发人员工具,我能够在 iframe 中找到我正在寻找的每个元素。在切换到 iframe 之前和之后,我都尝试通过 xpath 引用这些元素,但没有成功。此页面上只有 1 个 iframe。

在调试时,我尝试通过以下方式在 iframe 中查找任何元素:

webDriver.$(`iFrame`).$(`*`).getText()
webDriver.$(`iFrame`).$(`*`).isExisting()

或者切换到iframe之后:

webDriver.$(`*`).getText()
webDriver.$(`*`).isExisting()

在这两种情况下,它们都不返回任何内容:``

我已尝试更新框架以查看是否存在问题,并尝试了 Chrome 和 Firefox,结果相同。

以前有没有其他人遇到过类似的 iframe 问题?

【问题讨论】:

  • 您尚未提供网站的任何详细信息,或提供帮助的元素视图。因此,我在下面的答案中提供了我与团队一起做的培训示例,看看这是否对您有帮助

标签: iframe webdriver


【解决方案1】:

在 webdriver.io 上,将上下文切换到 iframe 的命令是 browser.switchToframe('locatorForYourIFrame')

https://webdriver.io/docs/api/webdriver#switchtoframe

【讨论】:

    【解决方案2】:

    这是我使用公共网站向我的团队展示的示例(语言:java - 没有具体说明,但原则可以适用于其他硒风味)。网站通过网站上的 iframe 弹出同意表(允许使用 cookie、日期等)。在下图中,来自网页 DOM 的 xpath 内容有一个高亮块来标识以下内容:

    1. iframe - 绿框
    2. 我们要在 iframe 内点击的按钮 (WebElement) - 红色框

    下面是使用 selenium java 和 chromedriver/浏览器的代码,这可以重新安装到其他 selenium 风格/浏览器

    ChromeOptions options = new ChromeOptions();
    options.setAcceptInsecureCerts(true);
    ChromeDriver driver = new ChromeDriver(options);
    
    //Navigate to website
    driver.get("https://www.empireonline.com");
    
    //Find number of iframes on the page
    int iframeCount = driver.findElements(By.tagName("iframe")).size();
    System.out.println("Number of Frames on a Page: "+iframeCount);
    
    //Locate the iframe by id
    WebElement iframe1=driver.findElement(By.id("sp_message_iframe_452327"));
    
    //Switch to the iframe
    driver.switchTo().frame(iframe1);
    
    //Locate the element within the iframe and click(in this case the 'Accept All' button)
    WebElement iframe1Button = driver.findElement(By.xpath("//button[contains(@title,'Accept All')]"));
    iframe1Button.click();
    
    //Switch back to the main webpage
    driver.switchTo().defaultContent();
    

    您可以使用任何可用的选项来定位 iframe,如图所示,iframe 有一个标题标签,因此也可以通过 xpath 定位,见下文:

    //Locate the iframe by xpath using the title tag
    WebElement iframe1=driver.findElement(By.xpath("//iframe[contains(@title,'SP Consent Message')]"));
    

    【讨论】:

      猜你喜欢
      • 2016-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-21
      • 2021-10-13
      相关资源
      最近更新 更多