2013-04-12 121 views
1

我有以下的HTML代碼,我需要選擇突出顯示的元素。如果菜單高亮顯示,我想選擇菜單中的按鈕而不是菜單!如果菜單是賽場,我想選擇它。選擇按鈕的XPath?

<menu id="apl" class="highlight" widgetid="apl"> 
<button id="navi" selectable="true" widgettype="button" widgetid="audio_radio_apl_navi"> 
<button id="audio" class="highlight" selectable="true" widgettype="button" widgetid="audio_radio_apl_audio"> 
<button id="tel" selectable="true" widgettype="button" widgetid="audio_radio_apl_tel"> 
<button id="video" selectable="true" widgettype="button" widgetid="audio_radio_apl_video"> 
<button id="system" selectable="true" widgettype="button" widgetid="audio_radio_apl_system"> 
<button id="net" selectable="true" widgettype="button" widgetid="audio_radio_apl_net"> 
</menu> 
<menu id="plf" widgetid="plf"> 
<img src="img/plf_radio.png"/> 
</menu> 

到目前爲止我的代碼是:

focusedElement = driver.findElement(By.xpath("//*[contains(@class,'highlight')]")); 

這讓我突出顯示的菜單,但我需要的按鈕! 任何想法?

+0

你能定義一下'如果菜單是賽場,我想選擇那'意味着你? – predi

+0

如果我選擇一個菜單,然後選擇菜單[@ class,'highlight']。但我不想選擇菜單元素。我想要突出顯示的按鈕,這是突出顯示的菜單的子項。如果菜單[@ id,'plf']那麼我想要菜單,因爲它沒有按鈕。 –

回答

0

如果我正確理解你的問題,這個XPath應該適用於你提供的例子。

//menu[@class='highlight']//button[@class='highlight'] 

它將尋找一個<menu>用含有<button>class='highlight'

+0

出錯了:org.openqa.selenium.InvalidSelectorException:給定的選擇器// * [contains(@ class,'highlight')]] // button [@ class ='highlight']無效或不會導致一個WebElement。 –

+0

在例外情況下顯示的XPath對許多人有一個']'。 – ellak

+0

對不起,在代碼中修復仍然沒有工作.. –

2

試試這個

focusedElement = driver.findElement(By.xpath("//button[@class='highlight']")); 

簡單,因爲它可以獲取或

Select selectBox = new Select(driver.findElement(By.xpath("//menu[@id='apl']"))); 
0

檢查class='highlight'突出顯示的元素有i是否改變了。 有時它是由javascript觸發的,並創建一個新元素,這是一個很難測試的問題。 還是上面的iFrame提到:d

0

你需要的條件語句: 你應該檢查是否元素"//menu[@id='apl']/button[@class='highlight']"存在,如果有,點擊它,如果沒有,然後點擊"//menu[@id='plf']"

0
focusedElement = driver.findElement(By.xpath("//menu[@id='apl']/button[2]"));