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

守給你的承諾、 提交于 2021-01-05 06:46:10

问题


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()

回答1:


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")
    



回答2:


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.



来源:https://stackoverflow.com/questions/55488606/typeerror-str-object-is-not-callable-using-selenium-through-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!