Selenium-Java如何将浏览器实例传递给其他方法
解决Selenium子方法复用浏览器实例的问题
嘿,我看你遇到的问题是子方法总是新开浏览器实例,没法复用main里已经打开的那个对吧?这其实是因为你在methode_two里又重新做了一遍浏览器驱动配置,还新建了FirefoxDriver实例——这就相当于又启动了一个全新的浏览器进程,当然和main里的不是同一个啦!
下面给你两个简单的解决方案,都是围绕复用同一个WebDriver实例来的:
方案1:把WebDriver作为参数传递给子方法
这是最直观也最适合新手的方式,直接把main里创建好的driver对象传给子方法就行:
- 修改
methode_two的方法签名,添加WebDriver driver作为参数 - 删掉子方法里重复的系统配置(
System.setProperty那些)和WebDriver driver = new FirefoxDriver();这行代码 - 调用子方法的时候把main里的driver传进去
修改后的完整代码如下:
package test; import org.openqa.selenium.*; import org.openqa.selenium.firefox.FirefoxDriver; import javax.swing.JOptionPane; import javax.swing.JDialog; import java.util.List; import java.util.Objects; import java.util.Scanner; public class automationtest { public static void main(String[] args) { String projectLocation = System.getProperty("user.dir"); System.setProperty("webdriver.gecko.driver", projectLocation+"\\lib\\Geckodriver\\geckodriver.exe"); System.setProperty("webdriver.firefox.bin", "C:\\Program Files\\Mozilla Firefox\\firefox.exe"); // 这里创建唯一的浏览器实例 WebDriver driver = new FirefoxDriver(); driver.navigate().to("some website"); //..... //doing loads of stuff on the website (works perfectly fine) //..... // 调用子方法时把driver传进去 methode_two(driver, value1, value2, value3, value4); } // 修改方法签名,添加WebDriver参数 public static void methode_two(WebDriver driver, int value1,int value2,int value3,int value4) { // 删掉重复的系统配置和driver初始化,直接用传进来的driver //doing some stuff on the website //比如:driver.findElement(By.cssSelector("div.field:nth-child(5) > input:nth-child(1)")).click(); } }
方案2:把WebDriver声明为类的静态成员变量
如果你觉得传参麻烦,也可以把driver声明成类的静态变量,这样整个类里的方法都能直接访问它:
package test; import org.openqa.selenium.*; import org.openqa.selenium.firefox.FirefoxDriver; import javax.swing.JOptionPane; import javax.swing.JDialog; import java.util.List; import java.util.Objects; import java.util.Scanner; public class automationtest { // 声明静态WebDriver变量 private static WebDriver driver; public static void main(String[] args) { String projectLocation = System.getProperty("user.dir"); System.setProperty("webdriver.gecko.driver", projectLocation+"\\lib\\Geckodriver\\geckodriver.exe"); System.setProperty("webdriver.firefox.bin", "C:\\Program Files\\Mozilla Firefox\\firefox.exe"); // 初始化静态driver driver = new FirefoxDriver(); driver.navigate().to("some website"); //..... //doing loads of stuff on the website (works perfectly fine) //..... // 直接调用子方法,不用传参 methode_two(value1, value2, value3, value4); } public static void methode_two(int value1,int value2,int value3,int value4) { // 直接使用类的静态driver变量 //doing some stuff on the website //比如:driver.findElement(By.cssSelector("div.field:nth-child(5) > input:nth-child(1)")).click(); } }
小提醒:不管用哪种方式,记得在测试结束后调用driver.quit();来关闭浏览器哦,不然会残留浏览器进程~
内容的提问来源于stack exchange,提问作者Dena
相关产品推荐
相关产品推荐

