Selenium python试图从下拉列表中提取第一个选定的选项值

时间:2017-03-03 15:32:07

标签: python selenium

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

这是我到目前为止所尝试的:

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

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

以下是HTML代码:

enter image description here

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

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)

1 个答案:

答案 0 :(得分:0)

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