2017-02-14 14 views
1

我想從ajax中獲取選項的值。 HTML代碼是:硒使用靜態ID獲取ajax的值

<select id="j_id0:searchlayout:mainform:countryVal" name="j_id0:searchlayout:mainform:countryVal" size="1" onchange="A4J.AJAX.Submit('j_id0:searchlayout:mainform',event,{'similarityGroupingId':'j_id0:searchlayout:mainform:j_id17','parameters':{'j_id0:searchlayout:mainform:j_id17':'j_id0:searchlayout:mainform:j_id17'} ,'status':'j_id0:searchlayout:mainform:statusProcess'})" style="height:2.4em;width:65%;"> 

<option value="" selected="selected">Select Country</option> 

正如你所看到的,因爲id的HMTL代碼中,使用webdriverWait(下)沒有幫助。

dropdownCountry = WebDriverWait(driver, 10).until(EC.presence_of_element_located(
    ((By.ID, "j_id0:searchlayout:mainform:countryVal"))) 

我試圖

dropdownCountry = wait.until(EC.element_to_be_clickable((By.XPATH, "//select[@id='j_id0:searchlayout:mainform:countryVal']/option"))) 

,但它不會產生一個列表。

一個選項是使用time.sleep(),給驅動程序足夠的時間來加載國家列表。但我知道這不是一個好習慣。

任何建議表示讚賞。 感謝

+0

我認爲這不是一個壞習慣 –

+0

或使用 - > http://selenium-python.readthedocs.io/waits.html#implicit-wa它的 –

回答

0

儘量等到option存在與不是空value屬性:

dropdownCountry = WebDriverWait(driver, 10).until(EC.presence_of_element_located(
((By.ID, "j_id0:searchlayout:mainform:countryVal"))) 
dropdownCountry.click() 
WebDriverWait(driver, 10).until(lambda driver: driver.find_element_by_xpath("//select[@id="j_id0:searchlayout:mainform:countryVal"]/option[not(@value='')]")) 
list_of_options = [option.get_attribute('value') for option in driver.find_elements_by_xpath("//select[@id="j_id0:searchlayout:mainform:countryVal"]/option[not(@value='')]")] 

你也可能需要等到option與文本內容是從"Select Country"不同顯示:

WebDriverWait(driver, 10).until(lambda driver: driver.find_element_by_xpath("//select[@id="j_id0:searchlayout:mainform:countryVal"]/option[not(text()='Select Country')]")) 
+0

謝謝,但我得到這個錯誤: raise exception_class(message,screen,stacktrace) selenium.common.exceptions.StaleElementReferenceException:消息:{「errorMessage」:「緩存中不存在元素」,「請求」: {「報頭」:{「接受」:「應用/ JSON」,「接受編碼」:「同一性」,「連接」:「關閉」,「內容長度」:「150」,「內容類型」: 「應用程序/ JSON;字符集= UTF-8」, 「主機」: 「127.0.0.1:45065","User-Agent":"Python-urllib/2.7"},"httpVersion":"1.1","method」 :「POST」,「post」:「{\」using \「:\」xpath \「,\」sessionId \「:\」b423c780-f2cd-11e6-8ec9-c1dae4070b7f \「, – nakisa

+0

我想這是因爲after 'dropdownCountry.click()''''''''''''''刷新''XHR''的整個'select'元素。檢查更新後的答案 – Andersson

+0

不,我嘗試不使用.click()。錯誤是一樣的。 – nakisa