当前位置: 代码迷 >> python >> 如何获得选择的选项(Selenium和Python)
  详细解决方案

如何获得选择的选项(Selenium和Python)

热度:85   发布时间:2023-06-16 10:18:41.0

我有一个问题,因为我想获得所选的选项名称:在这种情况下为Option3。 我想使用断言检查在这种情况下是否正确选择了值。 您可以在下面看到我的页面的一部分:

 <html> <body> <table border="0" cellpadding="0" cellspacing="0" class="rich-toolbar " id="mainMenuToolbar" width="100%"> <tbody> <tr valign="middle"> <td class="rich-toolbar-item " style=";"> <form id="substituteForm" name="name" method="post" action="http://homepage/home.seam" enctype="application/x-www-form-urlencoded"> <select name="substituteForm:j_id158" size="1" onchange="document.getElementById(&#39;substituteForm:substituteSubmit&#39;).click();"> <option value="0">Option0</option> <option value="1">Option2</option> <option value="2" selected="selected">Option3</option> </select> </form> </td> </tr> </tbody> </table> </body> </html> 

我使用DevTool复制XPath,并编写了代码:

element = Select(driver.find_element_by_xpath("//*   [@id='substituteForm']/select"))

而且我有错误信息:

selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: //*[@id='substituteForm']/select

我尝试了许多XPath组合,但仍然无法使用。

这似乎是时间问题,但不是XPath

尝试使用下面的代码等待直到目标select元素出现在DOM

from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait as wait

select = wait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "//form[@id='substituteForm']/select")))
select.click()
selected_option = wait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "//option[@selected='selected']")))
assert selected_option.text == "Option3"
  相关解决方案