【问题标题】:TypeError: 'str' object is not callable using Selenium through PythonTypeError:“str”对象不能通过 Python 使用 Selenium 调用
【发布时间】:2019-08-24 14:18:18
【问题描述】:

当我尝试执行下面显示的代码时出现错误:

TypeError: 'str' 对象不可调用

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

【问题讨论】:

    标签: python selenium selenium-webdriver properties webdriver


    【解决方案1】:

    text 是一个属性,而不是一个函数。不使用()

    element.text
    

    作为旁注,绝对 xpath "/html/body/..." 是一种不好的方法,它会使定位器变得脆弱。您应该尝试通过唯一属性(idnameclass 等)或至少相对的xpath 来定位元素。

    【讨论】:

      【解决方案2】:

      此错误消息...

      TypeError: 'str' object is not callable
      

      ...暗示你的程序调用了function(),实际上是property

      根据selenium.webdriver.remote.webelement textproperty

      因此,您不能将text() 作为函数调用。因此您会看到错误。

      解决方案

      您可以使用以下任一解决方案:

      • 使用text属性

        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
        
      • 使用get_attribute("innerHTML")方法:

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

      【讨论】:

      • get_atribute 的第二种方法和文本一样吗?
      • @szymond45 是的,imo,get_attribute("innerHTML") 更有希望。
      猜你喜欢
      • 2019-01-28
      • 2020-11-06
      • 2023-01-15
      • 2020-05-24
      • 1970-01-01
      • 2020-04-11
      • 2022-01-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多