Selenium-WebDriver Sleep()被忽略,而switchTo()更改了上下文

时间:2019-08-21 18:37:18

标签: selenium-webdriver webdriver

我是使用Selenium WebDriver的初学者,我想运行一些测试,包括单击按钮,填充文本区域然后比较一些文本,目前我遇到了两个问题,这是我的代码:< / p>

    var webdriver = require('selenium-webdriver'),
    By = webdriver.By,
    until = webdriver.until;
    var driver = new webdriver.Builder().forBrowser('chrome').build();
    driver.get('somepage');
    driver.findElement(By.id('button-id')).then(function(el) {
        console.log("Button found");
        driver.sleep(1000);
        el.click();
        // After click move to an iframe insde the page and do more stuff
        driver.switchTo().frame(0);
    });

运行此命令将返回错误element reference: element is not attached to the page document,我将其缩小为帧切换,从而更改了上下文,在该上下文中,驱动程序搜索按钮元素,而在找到该按钮之后却执行了该命令,在注释该行时,我在控制台中收到了消息但是然后立即单击了按钮,我也尝试了隐式和显式等待,它们被完全忽略了。这是我的package.json:

{
  "name": "testing",
  "version": "1.0.0",
  "description": "",
  "main": "chat-questions.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "chromedriver": "^76.0.0",
    "selenium-webdriver": "^4.0.0-alpha.4"
  }
}

有人知道为什么忽略睡眠并在执行之前更改框架吗? 我该如何解决?原因是什么?预先感谢。

1 个答案:

答案 0 :(得分:1)

您缺少 等待

检查一些示例以熟悉语法 Test Example 1Test Example : element_finding_test.js

    var webdriver = require('selenium-webdriver'),
    By = webdriver.By,
    until = webdriver.until;
    var driver = new webdriver.Builder().forBrowser('chrome').build();
    await driver.get('somepage');
    driver.findElement(By.id('button-id')).then(function(el) {
        console.log("Button found");
        await  driver.sleep(1000);
        await  el.click();
        // After click move to an iframe insde the page and do more stuff
        await driver.switchTo().frame(0);
    });