Selenium-使用NodeJS中的selenium-webdriver库与浏览器会话进行交互

时间:2018-08-28 12:46:34

标签: javascript node.js selenium selenium-webdriver

http://tarunlalwani.com/post/reusing-existing-browser-session-selenium/

这篇文章提供了使用现有会话进行硒的见解,但这是Python / Java语言。希望使用selenium-webdriver库在NodeJS中实现相同的逻辑。

我可以使用以下方式访问会话ID:

    driver.getSession().then( function(session) {
         console.log('Session:'+session.getId());
    });

但是如何获得执行者的价值呢?

经过仔细检查并发现的webdriver.WebDriver.attachToSession方法将附加到现有会话,但是需要执行者和会话的值相同。

2 个答案:

答案 0 :(得分:1)

可以使用Node附加到现有的webdriver会话

您只需要手动创建WebDriver对象,而无需构建器。

const _http = require('selenium-webdriver/http');

//todo: replace with your session ID and selenium url
let sessionId = 'cddab287623789c665c1dbc5c64bf702';
let url = 'http://localhost:4444/wd/hub';

let driver = new WebDriver(
    sessionId,
    new _http.Executor(Promise.resolve(url)
        .then(
            url => new _http.HttpClient(url, null, null))
    )
);

更复杂的示例:测试将尝试使用现有会话,如果它不起作用-将创建一个新会话。

const {Builder, By, Key, until, WebDriver} = require('selenium-webdriver');
const _http = require('selenium-webdriver/http');

(async function example() {
    //todo: replace this value with session ID after test is executed first time
    let sessionId = 'cddab287623789c665c1dbc5c64bf702';
    let url = 'http://localhost:4444/wd/hub';
    let browser = 'chrome';
    let startUrl = 'http://www.google.com/ncr';

    //Connect to existing session
    let driver = await new WebDriver(
        sessionId,
        new _http.Executor(Promise.resolve(url)
            .then(
                url => new _http.HttpClient(url, null, null))
        )
    );

    //Trying to open URL. If does not work - we need to re-create a session
    await driver.get(startUrl).catch(async r => {
        console.log('Session "' + sessionId + '" not found. Creating new session.');
        driver = await new Builder()
            .usingServer(url)
            .forBrowser(browser)
            .build();
        driver.getSession().then(function(e){
            console.log('Session: ' + JSON.stringify(e, null, 2));
        });
        driver.get(startUrl);
    });

    console.log('Starting test execution');

    try {
        await driver.findElement(By.name('q')).sendKeys('webdriver', Key.RETURN);
        await driver.wait(until.titleIs('webdriver - Google Search'), 1000);
    } finally {
        //todo: We intentionally do not close the session in order to use it next time
        // await driver.quit();
    }
})();

答案 1 :(得分:0)

为了使启动和重用WebDriver会话更加容易 我已经创建了一个脚本并将其打包在NPM软件包中,以便您可以在一个命令中启动或重用WebDriver会话。

npx webdriver-reuse-session

有关更多信息,请参见github自述文件。

然后您可以从Maksym中更改脚本,

//todo: replace with your session ID and selenium URL
let sessionId = 'cddab287623789c665c1dbc5c64bf702';

let sessionId = fs.readFileSync('.seleniumSessionId.txt')

然后,每次您开始测试时,此信息都会自动更新。

希望这对您或其他人有帮助。

相关问题