首页 > 解决方案 > Selenium wait until 不等到元素可见

问题描述

我正在使用 NodeJS、Mocha 和 Selenium 来自动填写我的时间表,我在等待登录表单时遇到了问题。

URL“https://timesheet.mydomain.com/timesheet.aspx”将打开重定向到我公司的登录页面,我需要等到登录输入可见。

用户名文本框可以通过 id - userid 识别,我添加了以下行以等待它的可见性。但是,它无法等待并显示以下错误。

我该如何解决 ?我试图在 Stackoverflow 和其他论坛中已经回答的问题中找到解决方案,但没有得到任何解决方案。请帮助解决这个问题。

量角器异步/等待错误:未处理的承诺拒绝

const { Builder, By, Key, until } = require('selenium-webdriver')
const assert = require('assert')

describe('Timesheet', function() {
  this.timeout(30000)
  let driver
  let vars
  beforeEach(async function() {
    driver = await new Builder().forBrowser('chrome').build()
    vars = {}
  })
  afterEach(async function() {
    await driver.quit();
  })
  it('Timesheet', async function() {
    await driver.get("https://timesheet.mydomain.com/timesheet.aspx")
    await driver.manage().window().setRect(1920, 1053)
    await driver.wait(until.elementIsVisible(await driver.findElement(By.id("userid"))), 60000)
    await driver.findElement(By.id("userid")).sendKeys("userid@mydomain.com")
    await driver.findElement(By.id("userid")).sendKeys(Key.ENTER)
  })
})

./node_modules/.bin/mocha timeSheet.js

       Timesheet:
     NoSuchElementError: no such element: Unable to locate element: {"method":"css selector","selector":"*[id="userid"]"}
  (Session info: chrome=83.0.4103.116)
      at Object.throwDecodedError (node_modules/selenium-webdriver/lib/error.js:550:15)
      at parseHttpResponse (node_modules/selenium-webdriver/lib/http.js:565:13)
      at Executor.execute (node_modules/selenium-webdriver/lib/http.js:491:26)
      at processTicksAndRejections (internal/process/task_queues.js:97:5)
      at async Driver.execute (node_modules/selenium-webdriver/lib/webdriver.js:700:17)
      at async Context.<anonymous> (timeSheet.js:18:46)

标签: node.jsseleniumselenium-webdrivermocha.js

解决方案


您是否尝试过让 selenium 尝试通过 XPath 查找元素?有时它找不到 ID,我只使用 XPaths,因为它们曾经工作过。那么它将是:

 it('Timesheet', async function() {
    await driver.get("https://timesheet.mydomain.com/timesheet.aspx")
    await driver.manage().window().setRect(1920, 1053)
    await driver.wait(until.elementIsVisible(await driver.findElement(By.XPATH("XPATH"))), 60000)
    await driver.findElement(By.XPATH("XPATH")).sendKeys("userid@mydomain.com")
    await driver.findElement(By.XPATH("XPATH")).sendKeys(Key.ENTER)

您还可以使用隐式等待方法,如下所示:

driver.implicitly_wait(15) #seconds to wait
await = driver.find_element_by_xpath("//*[@id='--ID--']") #Put in ID or XPATH
await.click() #If the driver is able to find the element within the time you set it to wait for, it will go on doing everything written under the implicitly wait line

推荐阅读