javascript - 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
问题是:为什么会发生这种情况?我不太喜欢选择带有数字的数组元素,但实际上我是被迫的,我不明白为什么其他选择器不起作用。
解决方案
这行代码...
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)
推荐阅读
- python - Sklearn GaussianProcessRegressor 修复内核超参数?
- javascript - 使用文字点符号设置器将属性注入 ReactJS 功能组件是一种好习惯吗?
- selenium - Robot Framework - Selenium Library 中 @BeforeTest 注释的替代品是什么?
- javascript - react-leaflet 中过滤标记的性能缓慢
- buffer-overflow - 缓冲区溢出 - 打印主机/用户名
- opengl-es - 在 opengl ES 中,我可以将顶点缓冲区数组缓冲区等用于着色器共享矩阵吗?
- python - 如何在 python-django 中水平查看元素
- javascript - 获取 javascript .val() 并在 iframe 的 URL 中使用它
- node.js - 无服务器节点 TypeScript 应用程序无法导入模块
- angular - 将响应字符串解析为 Angular2+ 中的对象