【问题标题】:Select element not returning webelement from .first_selected_option() method选择元素不从 .first_selected_option() 方法返回 webelement
【发布时间】:2013-06-03 14:57:14
【问题描述】:

我目前在编写一种方法时遇到了一些困难,该方法允许我在 Select 元素中找到当前选定选项的值。

<select id="select_foo_bar">
   <option value="0">FOO</option>
   <option value="1" selected="selected">BAR</option>
   <option value ="2">FOOBAR</option>
</select>

目前我有这个:

def find_selected_option(self):
    self.wait.until(EC.presence_of_element_location((By.ID, "select_foo_bar"))
    option = Select(self.driver.find_element_by_id("select_foo_bar")).first_selected_option()
    return option.get_attribute("value")

据我了解,该方法会找到option 元素,获取value 并返回它。

很遗憾,我收到了错误 TypeError: 'WebElement' object is not callable。这发生在option = Select(self.driver.find_element_by_id("select_foo_bar")).first_selected_option() 行上。它甚至没有达到return 声明的重点。

如有任何帮助,我们将不胜感激。

【问题讨论】:

  • 您是否尝试过通过分解以option = 开头的行进行调试,因此您首先将&lt;select&gt; 作为WebElement,然后(在新行上)强制转换为Select,然后再尝试调用 first_selected_option 方法?
  • 嗨@vincebowdren,我可能应该在之前提到过,我已经将其多次分解为局部变量。在逐步执行的过程中,它成功地到达了 Select 类中的 .first_selected_option() 方法。正如我所料,它确实通过循环并返回第二个选项。然而,在那之后,我收到了上面详述的错误。
  • 当您第一次发现&lt;select&gt; 作为WebElement 时,您可以在其上调用方法吗?还是只有在您将其转换为 Select 之后,方法调用才会失败?
  • 它很好地找到了元素,很好地投射它并循环遍历选项以找到“选定”选项。那时它似乎返回了那个WebElement,但它在找到它后就爆炸了。

标签: python selenium selenium-webdriver


【解决方案1】:

我已经解决了这个问题。是因为我昨天看文档累了。

需要调用的是first_selected_option,而不是first_selected_option()

感谢大家的帮助。

【讨论】:

    【解决方案2】:

    option = Select(... 行末尾是否缺少右括号?

    也许这就是你要找的东西:Selenium - Python - drop-down menu option value

    self.driver.find_element_by_id("select_foo_bar")应该已经返回了元素,你可以直接调用self.driver.find_element_by_id("select_foo_bar").first_selected_option()吗?

    【讨论】:

    • 啊,好地方,但不幸的是,那只是我愤怒的打字。已编辑。
    猜你喜欢
    • 2018-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-13
    • 1970-01-01
    • 2012-01-22
    • 2023-03-20
    • 1970-01-01
    相关资源
    最近更新 更多