How to get the current content of an element in webdriver

I have to think about it wrong.

I want to get the contents of an element, in this case a form field, on the page that I am accessing with Webdriver / Selenium 2

Here is my broken code:

Element=driver.find_element_by_id(ElementID) print Element print Element.text 

here is the result:

 <selenium.webdriver.remote.webelement.WebElement object at 0x9c2392c> 

(Note the empty line) I know that the element has content, since I just typed them there with the previous command using .sendkeys, and I can see them on the actual web page while the script is running.

but I need to return the contents to the data.

What can I do to read this? Generally preferred so that I can extract content from various types of elements.

+42
python selenium webdriver
Apr 20 '12 at 18:26
source share
4 answers

I believe that prestimism was on the right track. It depends on what element it is. You will need to use element.get_attribute('value') for the input elements and element.text to return the text of the node element.

You can check the WebElement object with element.tag_name to find out what the element is and return the corresponding value.

This will help you understand:

 driver = webdriver.Firefox() driver.get('http://www.w3c.org') element = driver.find_element_by_name('q') element.send_keys('hi mom') element_text = element.text element_attribute_value = element.get_attribute('value') print element print 'element.text: {0}'.format(element_text) print 'element.get_attribute(\'value\'): {0}'.format(element_attribute_value) driver.quit() 
+50
Apr 21 2018-12-12T00:
source share
 element.get_attribute('innerHTML') 
+3
Mar 27 '17 at 13:31 on
source share

My answer is based on this answer: How to get the current content of an element in webdriver just looks more like copy-paste.

 from selenium import webdriver driver = webdriver.Firefox() driver.get('http://www.w3c.org') element = driver.find_element_by_name('q') element.send_keys('hi mom') element_text = element.text element_attribute_value = element.get_attribute('value') print (element) print ('element.text: {0}'.format(element_text)) print ('element.get_attribute(\'value\'): {0}'.format(element_attribute_value)) element = driver.find_element_by_css_selector('.description.expand_description > p') element_text = element.text element_attribute_value = element.get_attribute('value') print (element) print ('element.text: {0}'.format(element_text)) print ('element.get_attribute(\'value\'): {0}'.format(element_attribute_value)) driver.quit() 
0
Sep 20 '17 at 9:41 on
source share

In Java, its Webelement.getText (). Not sure about python.

-5
Apr 21 2018-12-12T00:
source share



All Articles