TypeError: 'str' object is not callable using Selenium through Python
Asked Answered
P

3

8

When I try to do code shown below I get error :

TypeError: 'str' object is not callable

email2_elem = driver.find_element_by_xpath("/html/body/div[1]/div[2]/div[1]/div[1]/div[1]/form[1]/div[1]/input[1]").text()
Peursem answered 3/4, 2019 at 6:39 Comment(0)
K
17

This error message...

TypeError: 'str' object is not callable

...implies that your program have invoked a function() which is actually a property.

As per selenium.webdriver.remote.webelement text is a property.

So, you can't invoke text() as a function. Hence you see the error.

Solution

You can use either of the following solutions:

  • Use text property:

    email2_elem = driver.find_element_by_xpath("/html/body/div[1]/div[2]/div[1]/div[1]/div[1]/form[1]/div[1]/input[1]").text
    
  • Use get_attribute("innerHTML") method:

    email2_elem = driver.find_element_by_xpath("/html/body/div[1]/div[2]/div[1]/div[1]/div[1]/form[1]/div[1]/input[1]").get_attribute("innerHTML")
    
Knobby answered 3/4, 2019 at 11:34 Comment(2)
second method with get_atribute does same thing as just text?Peursem
@Peursem Yes, imo, get_attribute("innerHTML") is much more promising.Knobby
O
5

text is a property, not a function. Use it without ()

element.text

As a side note, absolute xpath "/html/body/..." is a bad approach, it makes fragile locator. You should try locating the elements by unique attribute (id, name, class etc), or atleast relative xpath.

Ocieock answered 3/4, 2019 at 6:43 Comment(0)
L
0

Try this

find_element(By.XPATH, "class name")

Refer this documentation link

https://selenium-python.readthedocs.io/locating-elements.html#locating-elements

Lyle answered 8/10, 2022 at 8:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.