通过 fancybox2 设置 iframe ID 以允许 webdriver switchTo()->frame(id)

setting iframe ID via fancybox2 to allow webdriver switchTo()->frame(id)

我正在使用 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(单击 link 创建 iframe)时,我无法预测要传入的框架 ID:

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

iframe 始终使用 fancybox-iframe 的 class 生成,但会调用

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

return 什么都没有。

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

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

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

我不知道这里设置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;
    }

对于任何感兴趣的人,按照上面@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();