首页 > 解决方案 > 登录后保持会话 - selenium - javascript

问题描述

我正在尝试使用 selenium web driver 和 node js 自动化几个页面。我能够登录,但登录后我想使用由网络驱动程序启动的相同会话,以便我可以在会话保护页面上进行自动化测试。这是我的尝试

async function login(){
    Let  d =  await new Builder()
                        .forBrowser('chrome')
                        .build();
    await d.get('https://demo.textdomain.com/')
    await d.findElement(By.id('username')).sendKeys('admin ')
    await d.findElement(By.id('password')).sendKeys('admin');
    await d.findElement(By.css('button[type="submit"]')).click();
    d.getPageSource().then(function(content) {

            if(content.indexOf('Welcome text') !==-1 ) {
             console.log('Test passed');
             console.log('landing page');
             d.get('https://demo.textdomain.com/landingpage') //this is still going to login page as i cannot use the previous session 
            } else {
                console.log('Test failed');
                return false;
            }
            //driver.quit();
        });

}

login();

登录后我是否不小心丢弃了浏览器。

标签: javascriptseleniumpromiseautomationwebdriver

解决方案


SQA StackExchange上的类似问题,您可以存储和恢复当前会话的 cookie:

使用 Javascript:

// Storing cookies:
driver.manage().getCookies().then(function (cookies) {
    allCookies = cookies;
}); 

// Restoring cookies:
for (var key in allCookies) {
    driver.manage().addCookie(key, allCookies[key]);
}

推荐阅读