我們可以使用 Selenium webdriver 查詢表單和 iframe 內部的元素。html 文件中的表單由
讓我們看看一個帶有電子郵件和密碼欄位的表單。
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; public class FormElements{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver","C:\Users\ghs6kor\Desktop\Java\chromedriver.exe"); WebDriver driver = new ChromeDriver(); String url = "https://www.linkedin.com/"; driver.get(url); driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS); // identify elements driver.findElement(By.id("session_key")).sendKeys("bde@gmail.com"); driver.findElement(By.id("session_password")).sendKeys("test!23"); // submitting form with submit() driver.findElement(By.id("session_password")).submit(); driver.quit() } }
iframe/frame 在 html 文件中使用 <iframe> 或 <frame> 標籤標識。iframe 是嵌入在另一個 html 文件中的 html 文件。為了訪問 iframe 內部的元素,我們需要將焦點從主頁面切換到 iframe。
以下方法有助於在 iframe 之間切換 -
switchTo().frame(args) – 將 frame 索引作為引數傳遞給方法。iframe 的起始索引為 0。
語法 -
driver.switchTo().frame(0),切換到第一個 iframe。
switchTo().frame(args) - 將 frame 名稱或 id 作為引數傳遞給方法。
driver.switchTo().frame("nm"),切換到名稱為 nm 的 iframe。
switchTo.frame(args) - 將 frame web 元素作為引數傳遞給方法。
driver.switchTo().frame(f),切換到 web 元素為 f 的 iframe。
switchTo().defaultContent() – 從 iframe 切換焦點到父頁面。
driver.switchTo().defaultContent()
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; public class iFrameElement{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver","C:\Users\ghs6kor\Desktop\Java\chromedriver.exe"); WebDriver driver = new ChromeDriver(); String url = "https://the-internet.herokuapp.com/nested_frames"; driver.get(url); driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS); // switch to a iframe driver.switchTo().frame("frame-bottom"); // identify webelement WebElement m = driver.findElement(By.cssSelector("body")); System.out.println(" The text is: " +m.getText()); // shift to parent page driver.switchTo().defaultContent(); driver.close(); } }
2K+ 瀏覽量
透過完成課程獲得認證