首页 > 解决方案 > Selenium textarea - 在 Javascript 中 - 解释

问题描述

我有这段 html,它位于下拉列表下,在下拉元素中选择 somthing 后出现:

<div class="mx-0 w-100 row">
    <textarea id="notes" placeholder="Write here..." required="" class="form-control"> </textarea>
</div>

我想用 Selenium 点击它,写点东西然后退出 textarea。实际上我做到了,但结果取决于我使用的选择器,我不知道为什么:

这是我的代码实际工作:我使用等待元素可见并启用,因为上面的下拉菜单在打开时会覆盖文本区域。如果我不使用它们,则会出现“不可交互”错误。

const notes = await driver.wait(until.elementsLocated(By.css('textarea')), delay)
await driver.wait(until.elementIsVisible(notes[0]), delay)
await driver.wait(until.elementIsEnabled(notes[0]), delay)
await notes[0].sendKeys('Something to write')
// this TAB is for exiting from textarea, which let a button to appear
await notes[0].sendKeys(Key.TAB)

现在,如果不是我使用的第一行

const notes = await driver.wait(until.elementLocated(By.id('notes')), delay)

或者

const notes = await driver.wait(until.elementLocated(By.xpath('//*[@id="notes"]')), delay)

并明显替换notes[0]notes, 它给了我

ElementNotInteractableError: element not interactable

问题是:为什么会发生这种情况?我不太喜欢选择带有数字的数组元素,但实际上我是被迫的,我不明白为什么其他选择器不起作用。

标签: javascriptseleniumselenium-webdriverselenium-chromedriverselenium-ide

解决方案


这行代码...

const notes = await driver.wait(until.elementsLocated(By.css('textarea')), delay)

...作为注释工作是所有元素的列表,这些元素被识别为会By.css('textarea')导致一定的延迟elementsLocated(),幸运的是,第一个匹配元素即notes[0]是您想要的元素,并且您已经完成了。

当然,第一个匹配的元素使用或者By.id('notes')不是By.xpath('//*[@id="notes"]')您想要的元素。


解决方案

最好的解决方案是使定位器策略更精细,如下所示:

  • CSS

    const notes = await driver.wait(until.elementLocated(By.css("textarea.form-control#notes")), delay)
    
  • 路径

    const notes = await driver.wait(until.elementLocated(By.xpath("//textarea[@class='form-control' and @id='notes']")), delay)
    

推荐阅读