Common methods of Java+selenium

Selenium encapsulates useful methods by itself, such as hovering and handle acquisition, which can be called directly to achieve your own needs.

1. Multi-window switching

That is to obtain the handle of the page to realize the switching of the page. Take hao123 as an example to realize the effect. The code is as follows.

public static void main(String [] args) throws InterruptedException{
    
    
	System.setProperty("webdriver.chrome.driver","D:/software/learn/chromedriver_win32/chromedriver.exe");
	WebDriver driver = new ChromeDriver();
	driver.get("http://www.hao123.com");
	String firtHandle = driver.getWindowHandle();
	driver.findElement(By.linkText("hao123新闻")).click();
	Set<String> h = driver.getWindowHandles();
	for(String handle : h){
    
    
		System.out.print("当前遍历值为:"+handle);
		Thread.sleep(1000);
		if(handle != firtHandle){
    
    
			// 句柄切换
			driver.switchTo().window(handle);
		}
	}
	driver.findElement(By.linkText("一键登录")).click();
}

A screenshot of the jump is shown below.

2. Hover effect

Selenium has its own hover method, which can be called directly. Taking Baidu as an example, the main calling process is as follows.

driver.get("http://www.baidu.com");
Actions action = new Actions(driver);
// 设置位置点击和停留
action.clickAndHold(driver.findElement(By.linkText("设置"))).perform();
driver.findElement(By.className("setpred")).click();

The realization effect is as follows.
insert image description here

Guess you like

Origin blog.csdn.net/u012190388/article/details/130444396