Webdriverjs没有休眠语句,陈旧的元素引用

Webdriverjs no sleep statements stale element reference

本文关键字:陈旧 元素 引用 语句 休眠 Webdriverjs      更新时间:2023-09-26

我有以下代码块,使用动作序列执行以下操作:

  • 点击页面链接
  • 等待页面上的输入字段出现
  • 点击输入字段
  • 删除所有存在的文本
  • 发送一个键序列以进入一个位置
  • 点击向下箭头(输入使用自动完成)
  • 按回车键选择正确的位置
  • 点击保存按钮

我读到不建议使用driver.sleep()语句,但如果没有它们,我无法使代码正常工作。

下面是代码块:

driver.wait(until.elementLocated(By.css("a[href*='details/location']")), 5000)
driver.findElement(By.css("a[href*='details/location']")).click()
driver.wait(until.elementLocated(By.id("user_location")), 5000)
let loc = driver.findElement(By.id("user_location"))
let save = driver.findElement(By.xpath("//span[contains(text(), 'Save')]"))
driver.sleep(3000)
driver.actions().
    click(loc).
    sendKeys(Key.DELETE)
    .sendKeys('My location')
    .perform()
driver.sleep(1000)
driver.actions().
    sendKeys(Key.ARROW_DOWN).
    sendKeys(Key.ENTER).
    perform()
driver.sleep(1000)
driver.actions().
    click(save).
    perform()

是否有更好的方法去做这件事和/或有一种方法来删除sleep语句?为什么当我取出sleep语句时,会发生stale element错误?

一个问题可能是从抓取locsave页面到实际使用它们之间的时间。试着像下面这样重新排列代码,看看是否有帮助。

我注意到的另一件事,driver.wait()返回等待的元素,所以你可以组合行1 &第2行和第3行&这样你就不用刮两次了。

driver.wait(until.elementLocated(By.css("a[href*='details/location']")), 5000).click()
let loc = driver.wait(until.elementLocated(By.id("user_location")), 5000)
# driver.sleep(3000) # you shouldn't need this sleep?
driver.actions()
    .click(loc)
    .sendKeys(Key.DELETE)
    .sendKeys('My location')
    .perform()
driver.sleep(1000)
driver.actions()
    .sendKeys(Key.ARROW_DOWN)
    .sendKeys(Key.ENTER)
    .perform()
driver.sleep(1000)
let save = driver.findElement(By.xpath("//span[contains(text(), 'Save')]"))
driver.actions()
    .click(save)
    .perform()