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.
Use the textContent property to get the text of a span element, e.g. const text = span. textContent . The textContent property will return the text content of the span and its descendants. If the element is empty, an empty string is returned.
To identify the element with span tag, we have to first identify it with any of the locators like xpath, css, class name or tagname. After identification of the element, we can perform the click operation on it with the help of the click method. Then obtain its text with the text method.
We can locate elements in span class and not unique id with the help of the Selenium webdriver. We can identify an element having a class attribute with the help of the locator xpath, css or class name. To locate elements with these locators we have to use the By. xpath, By.
text() and contains methods text(): A built-in method in Selenium WebDriver that is used with XPath locator to locate an element based on its exact text value. contains(): Similar to the text() method, contains() is another built-in method used to locate an element based on partial text match.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With