Why is getText() in Selenium not working for <textarea> elements, but getAttribute(“value”) is?

白昼怎懂夜的黑 提交于 2020-12-31 04:55:03

问题


Given you have some HTML with a textarea element and want to get its text via Selenium (here Java-binding).

<textarea name="txtComment" id="txtComment" rows="2" cols="20">
    Some comment inside the textarea
</textarea>

This is how I see the code via developer tools (Internet Explorer and Firefox), so it seems like it is a normal text-node and not inside the "value" attribute of the element.

Why is it then that getText() does not work:

driver.findElement(By.id("txtComment")).getText();

It only returns an empty String.

But using getAttribute("value") works and results in returning the expected string:

driver.findElement(By.id("txtComment")).getAttribute("value");

This returns "Some comment inside the textarea" as expected

This is rather surprising since the Selenium documentation about getText() says the following:

Get the visible (i.e. not hidden by CSS) innerText of this element, including sub-elements, without any leading or trailing whitespace.

Returns: The innerText of this element.

As the HTML code in the beginning shows, the text-part of the element is visible and it is the "innerText", isn't it?

Can someone shed light on where I'm wrong or if I'm not, why is this implemented like this in Selenium?


回答1:


In Python, it gives the same result:

driver.find_element_by_id("txtComment").text
driver.find_element_by_id("txtComment").get_attribute("value")

Some comment inside the textarea.



来源:https://stackoverflow.com/questions/32379622/why-is-gettext-in-selenium-not-working-for-textarea-elements-but-getattribu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!