我们可以在与.properties文件一起使用的Properties类的帮助下在Selenium中声明全局变量。在.properties文件中,数据存储在键值对中。我们可以在.properties文件中读取和写入值。
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.Properties; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; public class Propert { public static void main(String[] args) throws IOException { //TODO自动生成的方法存根 Propert t = new Propert(); t.login(); } public void login() throws IOException { Properties prop = new Properties(); FileInputStream ips = new FileInputStream( "C:\\Users\\ghs6kor\\eclipse- workspace\\Inheritance\\config.properties"); prop.load(ips); // read from properties file with getProperty() method if (prop.getProperty("browser").equalsIgnoreCase("firefox")) { System.setProperty("webdriver.gecko.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\geckodriver.exe"); WebDriver driver = new FirefoxDriver(); driver.manage().window().maximize(); driver.get(prop.getProperty("url")); FileOutputStream ops = new FileOutputStream( "C:\\Users\\ghs6kor\\eclipse- workspace\\Inheritance\\config.properties"); String urlnm = driver.getTitle(); // writing in the properties file with setProperty() method prop.setProperty("title", urlnm); prop.store(ops, null); } } }