I have a webpage with javascript in which I've created a textarea like so
var textarea = $("<textarea>");
textarea.change(() => {
console.log(textarea.val());
});
So when I change the value in the textarea and then change focus, the value is printed. This works as expected when using a normal web browser.
However, I have a test using selenium firefox driver that edits the textarea. Two seperate textareas are created using the same bit of code similar to above. The first one works fine. But with the second, selenium finds the textarea, sends keys, and tabs away, but textarea.val()
returns an empty string. In the browser opened by selenium, I can see that the keys I sent are indeed entered in the textarea.
The code in my tests (python) that edits the textarea is
e.clear()
e.send_keys(s)
ActionChains(driver).key_down(Keys.TAB).perform()
And as I said, I can inspect the browser that selenium creates, and the text has been entered and I have tabbed away. I also know this works because the change callback is called.
So why would textarea.val()
in the js script return an empty string?
UPDATE 1
Another weird thing, if I leave the selenium-created browser open after the test fails and manually change the value in the textarea (the same exact one that just produced this error!), it works as expected! This led me to think it was some kind of timing issue. So I added 2 second sleep statements all over my test script, but no help.
UPDATE 2
While running my test with all the sleep statements, I notice that the first time the textarea is editted, the insert cursor appears in the textarea (as it should). But the second time, no cursor appears, even though the text is still entered properly using send_keys
. I tried adding e.click()
on the textarea after e.clear()
it, but the cursor still doesnt appear. Perhaps the lack of cursor is related to my issue.
答案 0 :(得分:0)
要从文本区域跳出标签,您需要按下标签键然后将其释放。您的代码未释放Tab键,这就是永远不会触发textArea.change()
的原因。将代码修改为
ActionChains(driver).key_down(Keys.TAB).key_up(Keys.TAB).perform()
答案 1 :(得分:0)
尝试过很多事情。尝试了GPT14的答案。尝试将我的element.click()语句更改为ActionChains语句,认为textarea可能没有正确聚焦。最后,唯一可行的是切换到Chrome驱动程序...
但仍然有奇怪的行为,textarea更改回调被调用两次。第一次,它给出一个空字符串。但第二次它返回当前值,因此我的测试能够继续。