【问题标题】:setting iframe ID via fancybox2 to allow webdriver switchTo()->frame(id)通过 fancybox2 设置 iframe ID 以允许 webdriver switchTo()->frame(id)
【发布时间】:2015-10-02 21:18:54
【问题描述】:

我正在使用fancybox2 创建 iframe,但我看不到设置所创建 iframe 的 ID 的方法,这使我无法使用 php-webdriver 和 selenium 来测试 iframe 的内容.

简化版代码:

<a href="iframe.html" class="various fancybox.iframe">iframe</a>

<script>
$(document).ready(function() {
    $(".various").fancybox()
});
</script>

这可行,但使用 Chrome 的检查器,iframe(这次)生成的 ID 为 fancybox-frame1443817733402,这似乎是随机的。这意味着当我尝试使用 php-webdriver 到 switch to this frame(点击链接创建 iframe)时,我无法预测要传入的框架 ID:

$frame_id = 'fancybox-frame1443817733402'; // can't predict this in advance
$driver->switchTo()->frame($frame_id);

iframe 始终使用 fancybox-iframe 类生成,但调用

$iframe = $driver->findElement(WebDriverBy::class("fancybox-iframe"))

什么都不返回。

我也尝试过使用 fancybox2 的 afterLoad 回调来尝试显式设置 iframe 的 ID,然后再尝试通过此 ID 切换到框架,但这也失败了(我认为因为 current 是一个对象,而不是一个元素?)

$(".various").fancybox({
    afterLoad: function(current, previous) {
        //console.log(current);
        current.attr('id', 'rob');
    }});

有没有办法明确设置 iframe 的 ID,以便我可以通过 selenium/webdriver 切换到它?或者有更简单的方法吗?

【问题讨论】:

    标签: php selenium selenium-webdriver fancybox-2


    【解决方案1】:

    这里不知道设置frame id,但是可以通过xpath切换到frame(比如//frame):

        protected WebElement gotoIframeByXpath(final String iframeXpath) {
            if (driver.findElements(By.xpath(iframeXpath)).size() > 0) {  // find elements so an exception isn't thrown if not found
                WebElement contentFrame = driver.findElement(By.xpath(iframeXpath));
                driver.switchTo().frame(contentFrame);
                return contentFrame;
            } else {
                System.out.println("Unable to find " + iframeXpath);
            }
            return null;
        }
    

    【讨论】:

    • 谢谢,这让我朝着正确的方向前进。我在下面添加了工作代码,因为我使用的是 PHP
    【解决方案2】:

    对于任何感兴趣的人,按照上面@EGHM 的回答,我就是这样做的。

    // this also works & is a little simpler
    //$iframes = $driver->findElements(WebDriverBy::tagName('iframe'));
    
    $iframes = $driver->findElements(WebDriverBy::xPath('//*[starts-with(@id,"fancybox-frame")]'));
    $id = $iframes[0]->getAttribute('id');
    
    $driver->switchTo()->frame($id);
    echo $driver->getPageSource();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多