我是硒新手。我正在嘗試測試一個應用程序。應用程序有兩個頁面login.jsp,restricted.jsp。只有在登錄後才能訪問restricted.jsp(嘗試訪問restricted.jsp而無需登錄將重定向到login.jsp頁面)。我的硒應用如下所示。Selenium:Cookie功能不起作用
a。首先登錄到應用程序
b。成功登錄後,將所有cookie存儲到「session.properties」文件中。
c。下一次,我將所有的cookie從「session.properties」加載到驅動程序,並嘗試訪問「restricted.jsp」頁面。但我重定向到login.jsp,而不是restricted.jsp。
以下是我的Java代碼。
public class App {
private static void loginApp(WebDriver driver) {
driver.get("http://localhost:8080/selenium_app/login");
WebElement userName = driver.findElement(By.name("userName"));
WebElement password = driver.findElement(By.name("password"));
userName.sendKeys("admin");
password.sendKeys("admin");
userName.submit();
}
private static void storeSessionProps(WebDriver driver) throws IOException {
File f = new File("session.properties");
f.delete();
f.createNewFile();
FileWriter fos = new FileWriter(f);
BufferedWriter bos = new BufferedWriter(fos);
/* Get all the cookies and store them to session.properties file */
Set<Cookie> cookies = driver.manage().getCookies();
for (Cookie cookie : cookies) {
bos.write(cookie.getName() + "=" + cookie.getValue());
bos.newLine();
}
bos.flush();
bos.close();
fos.close();
}
private static void loadPropertiesToDriver(WebDriver driver)
throws IOException {
Properties properties = new Properties();
FileInputStream fin = new FileInputStream("session.properties");
properties.load(fin);
Set<Object> props = properties.keySet();
for (Object prop : props) {
Cookie ck = new Cookie((String) prop,
properties.getProperty((String) prop));
driver.manage().addCookie(ck);
System.out.println(ck);
}
}
public static void main(String[] args) throws InterruptedException,
IOException {
WebDriver driver = new FirefoxDriver();
// loginApp(driver);
// storeSessionProps(driver);
loadPropertiesToDriver(driver);
driver.get("http://localhost:8080/selenium_app/restricted");
Thread.sleep(5000);
driver.quit();
}
}
當我取消線loginApp(駕駛員);, storeSessionProps(驅動器);一切都很好,我可以訪問restricted.jsp頁面,但是當我通過註釋和加載cookie運行應用程序時,我正在重定向到login.jsp頁面。對此有何幫助?
感謝您的回答,它解決了我的問題。 –