【问题标题】:Selenium python trying to extract the first selected option value from the dropdownSelenium python试图从下拉列表中提取第一个选定的选项值
【发布时间】:2017-03-03 15:32:07
【问题描述】:

我正在尝试从下拉列表中提取第一个选定的值。不知道我在这里错了什么

这是我迄今为止尝试过的:

currency = Select(self.driver.find_element_by_id("currencyid"))
currency.select_by_visible_text("AUD")

assert currency.first_selected_option().text == "AUD"

HTML 代码如下:

这是我遇到的错误,不确定这有多大用处:

File "Test.py", line 54, in test_TestOne
    assert currency.first_selected_option().text == "USD"
  File "C:\Python27\lib\site-packages\selenium\webdriver\support\select.py", line 62, in first_selected_option
    for opt in self.options:
  File "C:\Python27\lib\site-packages\selenium\webdriver\support\select.py", line 47, in options
    return self._el.find_elements(By.TAG_NAME, 'option')
  File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webelement.py", line 528, in find_elements
    {"using": by, "value": value})['value']
  File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webelement.py", line 494, in _execute
    return self._parent.execute(command, params)
  File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 236, in execute
    self.error_handler.check_response(response)
  File "C:\Python27\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 192, in check_response
    raise exception_class(message, screen, stacktrace)
StaleElementReferenceException: Message: stale element reference: element is not attached to the page document
  (Session info: chrome=56.0.2924.87)
  (Driver info: chromedriver=2.25.426923 (),platform=Windows NT 10.0.10586 x86_64)

【问题讨论】:

  • StaleElementReferenceException 表示selenium 查找了您的elementhtml 结构发生了变化(在找到您的select 之前页面上是否还有内容加载?),然后您尝试使用旧的“陈旧”元素。您最好的选择可能是在与下拉菜单交互之前等待指示页面已加载的内容。要测试这是问题所在,请在此Select(self.driver.find_element_by_id("currencyid")) 之前休眠几秒钟,如果可行,您可以弄清楚要等待什么。
  • 你想找到selected选项吗?
  • @mrfreester,不知道发生了什么。我尝试添加 5 秒睡眠,但它甚至不等待 5 秒。它立即给出了这个错误
  • @user7242550 assert currency.first_selected_option().text == "USD" 的这条线在哪里?我认为你在那里得到了你的陈旧元素,试着在那条线之前睡一觉。
  • @user7242550 如果它没有执行你的睡眠,那么你的睡眠代码实际上并没有在睡眠,或者它在该行之前失败。如果你确定你的睡眠代码是正确的,继续往上移动,直到你发现哪一行真的失败了

标签: python selenium


【解决方案1】:
currency = Select(self.driver.find_element_by_id("currencyid"))
currency.select_by_visible_text("AUD")

assert currency.first_selected_option.text == "AUD"

你应该使用first_selected_option 而不是first_selected_option()

【讨论】:

  • 我在你的代码中找不到assert currency.first_selected_option().text == "USD"
猜你喜欢
  • 1970-01-01
  • 2017-05-25
  • 1970-01-01
  • 2014-04-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-24
  • 1970-01-01
相关资源
最近更新 更多