Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the current contents of an element in webdriver

I must be thinking about this wrong.

I want to get the contents of an element, in this case a formfield, on a 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> 

(Notice the blank line) I know that element has contents since I just stuffed them in there with the previous command using .sendkeys and I can see them on the actual web page while the script runs.

but I need to get the contents back into data.

What can I do to read this? Preferably in a generic fashion so that I can pull contents from varied types of elements.

like image 659
Skip Huffman Avatar asked Apr 20 '12 18:04

Skip Huffman


People also ask

How do you get the content inside a tag in Selenium?

you can use xpath to get the text values. driver. findElement(By. xpath("//li[@id='li1']/div/p[1]")).

How do I extract text from web element?

Selenium extracts the text of a webelement with the help of getText() method. Code Implementation with getText().

How do you check if an element is present in a page in Selenium?

We can verify whether an element is present or visible in a page with Selenium webdriver. To check the presence of an element, we can use the method – findElements. The method findElements returns a list of matching elements. Then, we have to use the method size to get the number of items in the list.

How do I find an element that contains specific text in Selenium Webdriver?

We can find an element that contains specific text with Selenium webdriver in Python using the xpath. This locator has functions that help to verify a specific text contained within an element. The function text() in xpath is used to locate a webelement depending on the text visible on the page.


1 Answers

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

You could check the WebElement object with element.tag_name to find out what kind of element it is and return the appropriate value.

This should help you figure out:

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() 
like image 187
Isaac Avatar answered Sep 21 '22 17:09

Isaac