【问题标题】:Switching to iframes in Selenium-Java在 Selenium-Java 中切换到 iframe
【发布时间】:2017-01-23 12:00:59
【问题描述】:

我无法在窗口的 iframe 之间切换。我想在网页顶部窗口中选择一个 iframe。

页面的链接是: http://way2automation.com/way2auto_jquery/dropdown.php#example-1-tab-1

我可以找到两个 iframe,但无法切换到 iframe。每个 iframe 都有自己的下拉列表,我需要从中选择元素。

我尝试过使用 driver.switchto(),但它无法识别 iframe。

我的代码是:

    public void SimpleDropDown() throws InterruptedException {
        dr.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
//      dr.findElement(By.xpath("//a[text()='Select Country']")).click();
//      dr.switchTo().frame(dr.findElement(By.xpath("//div[@id='example-1-tab-1']//iframe")));
        Select dropdown = new Select(dr.findElement(By.xpath("html/body/select")));
        dropdown.selectByVisibleText("India");
        System.out.println(dropdown.getFirstSelectedOption().getText());
    }

    public void comboBox() {
        dr.switchTo().frame(2);
        dr.findElement(By.xpath("//a[text()='Enter Country']")).click();
        Select dropdown = new Select(dr.findElement(By.xpath("//select[@id='combobox']")));
        dropdown.selectByVisibleText("Portugal");

【问题讨论】:

  • Frame index with 0 用于first frame
  • 目标页面需要注册,因此您最好提供适当的HTML 代码。您还需要driver.switchTo().defaultContent(); 才能切换到下一个iframe

标签: selenium iframe xpath


【解决方案1】:

尝试执行这段代码。

WebElement iframe = driver.findElement(By.tagName("iframe"));
driver.switchTo().frame(iframe);                                //Move inside to the frame. 
WebElement body = driver.findElement(By.tagName("body"));
body.click();
driver.findElement(By.xpath("//a[text()='Enter Country']")).click();
Select dropdown = new Select(driver.findElement(By.xpath("//select[@id='combobox']")));
dropdown.selectByVisibleText("Portugal");
driver.switchTo().defaultContent();                            //Move outside to the frame.

【讨论】:

  • 如果解决了您的问题,请将此答案标记为已接受。因此,它也会对其他用户有所帮助。谢谢:)
【解决方案2】:

切换到起始索引为 0 的帧是可行的,但不是切换到默认帧,而是应该使用 switchTo().parentFrame(),因为它会返回到顶部窗口(仅当您不使用嵌套帧时)。

【讨论】:

    【解决方案3】:

    您的网站在同一页面中显示 2 个iFrames。因此,在选择下拉列表之前,您需要切换到 frame,因为您的下拉列表位于 iframe-

        driver.switchTo().frame(0);
        Select select = new Select(driver.findElement(By.tagName("select")));
        select.selectByValue("Angola");
    

    一旦你做出选择,需要使用 -

    driver.switchTo().defaultContent();
    

    然后导航到另一个选项卡,然后您的元素再次位于 iframe 下,因此需要再次执行相同的操作

        driver.findElement(By.xpath("//li/a[text()='Enter Country']")).click();
        driver.switchTo().frame(1);
        driver.findElement(By.xpath("//span[@class='custom-combobox']/input")).sendKeys("India");
        driver.switchTo().defaultContent();
    

    【讨论】:

      猜你喜欢
      • 2014-06-11
      • 1970-01-01
      • 2023-03-08
      • 1970-01-01
      • 2018-07-22
      • 2019-01-08
      • 2021-11-14
      • 2015-02-11
      • 1970-01-01
      相关资源
      最近更新 更多