java 语言 使用 selenium swithTo方法例子
时间: 2024-06-10 14:06:42 浏览: 132
Sure, Here is an example of using switchTo method in Selenium with Java:
```
// Initialize WebDriver
WebDriver driver = new ChromeDriver();
// Navigate to Google website
driver.get("https://www.google.com");
// Locate the search box input field
WebElement searchBox = driver.findElement(By.xpath("//input[@name='q']"));
// Enter search query
searchBox.sendKeys("Selenium");
// Press ENTER key
searchBox.sendKeys(Keys.ENTER);
// Switch to the new tab opened by Google search
ArrayList<String> tabs = new ArrayList<String> (driver.getWindowHandles());
driver.switchTo().window(tabs.get(1));
// Verify if search results page is displayed
WebElement searchResults = driver.findElement(By.xpath("//div[@id='result-stats']"));
if(searchResults.isDisplayed()){
System.out.println("Search results displayed.");
}
// Close the new tab
driver.close();
// Switch back to the original tab
driver.switchTo().window(tabs.get(0));
// Close the original tab
driver.close();
// Quit the WebDriver instance
driver.quit();
```
Note: This example navigates to Google, enters a search query and opens the search results page in a new tab. It then verifies if the search results page is displayed and closes the new tab. Finally, it switches back to the original tab and closes it before quitting the WebDriver instance.
阅读全文