How to get the text content of a text field using webdriver?

I am trying to get textarea content in HTML form using webdriver in Python .

I get text, but no new lines. selenium docs are almost useless; they speak:

class selenium.webdriver.remote.webelement.WebElement (parent, id _)

[...]

text: Gets the text of the element.

I am currently doing the following:

from selenium import webdriver # open the browser and web site b = webdriver.Firefox() b.get('http://www.example.com') # get the textarea element textbox = b.find_element_by_name('textbox') # print the contents of the textarea print(repr(textbox.text)) 

This prints a Unicode string representation of Python textarea content, except that all newlines have been replaced with spaces. Doh!

Not sure if I ran into a text encoding problem, a selenium / webdriver error (could not find it in the tracker), or a user error.

Is there any other way to do this?

EDIT : I just asked Chrome to try ... it works fine. I reported an error in selenium issue tracker. Sam's workaround (accepted answer below) works in Firefox with one caveat: characters are converted to HTML object codes in the returned string. This is not a big deal .

+7
source share
3 answers

As a workaround, you can try using ExecuteScript to get innerHtml. I'm not a python guy, but here he is in C #:

 IWebElement element = ... String returnText = ((IJavaScriptExecutor)webDriver).ExecuteScript("return arguments[0].innerHTML", element).ToString(); 
+4
source

I just got the tagarea attribute value. The following is sample Java code.

 WebElement textarea = driver.findElement(By.id("xf-1242")); String text = textarea.getAttribute("value"); log.debut(text); 

I am using the Chrome driver, and the above code puts the text (XML in my case) with new characters in the log. I got an idea from http://www.w3schools.com/jsref/dom_obj_textarea.asp

Jan

+7
source

In Python, first get the element and after receiving the attribute value, the function in python get_attribute ('value').

 from selenium import webdriver driver = webdriver.Firefox() URL = "http://www.w3schools.com/tags/tryit.asp?filename=tryhtml_textarea" driver.get(URL) driver.switch_to.frame("iframeResult") # get the textarea element by tag name textarea = driver.find_element_by_tag_name('textarea') # print the attribute of the textarea print(textarea.get_attribute('value')) print(textarea.get_attribute('rows')) print(textarea.get_attribute('cols')) 
0
source

All Articles