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