Reputation: 15339
This should be easy, but I can't get it to work. I'm running a little demo using the Google homepage as a test.
Here's my script:
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.keys import Keys
import time
browser = webdriver.Chrome()
browser.get("http://www.google.com") # Load page
time.sleep(0.2)
#top nav elements
elems = browser.find_elements_by_xpath("//span[contains(@class, 'gbts')]")
for e in elems:
print e.get_attribute('text')
browser.close()
It returns:
None
None
None
None
None
None
None
None
None
None
None
So I think it's grabbing the right elements, but perhaps not the right attribute? Not sure. I also tried to print e.text() but that spit out:
Traceback (most recent call last):
File "sample.py", line 14, in <module>
print e.text()
TypeError: 'unicode' object is not callable
Any thoughts?
*Edit - Possible Solution? *
e.get_attribute('innerHTML') seems to work.
Upvotes: 29
Views: 144538
Reputation: 281
YES ! Solution was found (I`am using Python) For instanc: webelement is a p tag
webelement.text()
from real situation, stacktrace:
print page_box_block.text() TypeError: 'unicode' object is not callable
it expect to be a html in stdout, but not !
sometimes could be a strange string "unicode object is not callable" or some type error solution is very easy:
print element.get_attribute("innerHTML")
In java get_attribute("innerHTML") and text() are about to "same", if you need plain text from element In Python 2.7 for now text() sometimes fails.
Upvotes: 21
Reputation: 80406
This should do it:
from selenium import webdriver
browser = webdriver.Firefox()
browser.get("http://www.google.com")
for elem in browser.find_elements_by_xpath('.//span[@class = "gbts"]'):
print elem.text
text
is a property of the WebElement
class, thus it is not callable.
class WebElement(object):
"""Represents an HTML element.
...
...
@property
def text(self):
"""Gets the text of the element."""
return self._execute(Command.GET_ELEMENT_TEXT)['value']
You have two alternatives to get the third match:
# 1. Modify your xpath expression
browser.find_elements_by_xpath('(.//span[@class = "gbts"])[3]')[0].text
# 2. Access it by list index
browser.find_elements_by_xpath('.//span[@class = "gbts"])')[2].text
Upvotes: 41