2017-02-16 4 views
1

이 경우 선택한 옵션 이름 : Option3을 얻으 려하므로 문제가 있습니다. 이 경우에는 값이 올바르게 선택되었는지 확인하기 위해 assert를 사용하고 싶습니다. 당신은 아래에있는 내 페이지의 일부를 볼 수 있습니다선택한 옵션 (Selenium & Python)을 얻는 방법

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

내가 XPath를 복사 DevTool을 사용

을 나는 코드 작성 :

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

을 나는 오류 메시지가 :

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

많은 XPath 조합을 시도했지만 여전히 작동하지 않습니다. .

답변

1

이 문제 타이밍 것으로 보이지만, 대상 select 요소가 DOM에 나타날 때까지하지 XPath

봅니다 기다려야 코드 아래 사용 :

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" 
+0

얍합니다. 이제 작동합니다. 감사 :) – Surion