如何在 Selenium 中处理框架?

software testingautomation testingselenium web driver

我们可以使用以下方法在 Selenium 中处理框架。

  • switchTo().frame(frameNumber)

    此方法使用框架 ID 作为参数。框架 ID 的索引从 0 开始。如果找不到框架,则会抛出 NoSuchFrameException 异常。

  • switchTo().frame(frameName)

    此方法使用开发者定义的框架名称作为参数。框架名称被视为字符串,并用引号括起来。如果找不到框架,则会抛出 NoSuchFrameException 异常。

  • switchTo().frame(WebElement)

    此方法使用 WebElement 作为参数。如果找不到框架,则会抛出 NoSuchFrameException 异常。

  • 如果框架不再处于活动状态,则会抛出 StaleElementReferenceException 异常。

示例

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class FrameSet {
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url = "url with frames";
      driver.get(url);
      driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);
      //借助索引获取第一帧
      driver.switchTo().frame(0);
      //借助帧名称抓取帧
      driver.switchTo().frame(“<<name expression>>“);
      //借助框架元件抓住框架
      WebElement name = driver.findElement(By.name(“frame-right”));
      driver.switchTo().frame(driver.findElement(By.name(“<<name expression”)));
      driver.quit();
   }
}

相关文章