2012-03-15 114 views
1

在Java類中使用Selenium WebDriver,我嘗試查找特定元素,然後在輸入字段中自動添加所需的元素數量。查找在Selenium WebDriver中使用的HTML元素

我有一個HTML表格,每行指定一個元素類型和一個輸入字段,用於將X添加到特定行中元素的數量。

<tr> 
    <td class="non-sortable-table"> 
    <input class="required text" type="text" value="0" name="plate_order{pageFlow.plateorders[0].numberOfPlates}" tabindex="25"> 
    </td> 
    <td class="non-sortable-table"> 
    <span>20% - White plates</span> 
    </td> 
    ... 
</tr> 

我試圖在我的Java代碼,以獲得該元素的下面,但沒有運氣:

WebElement element = (WebElement) js.executeScript("return ${\"document.getElementsByName('plate_order{pageFlow.plateorders[0].numberOfPlates}')\""); 

WebElement element = driver.findElement(By.ByName('plate_order{pageFlow.plateorders[0].numberOfPlates}')) 

我怎麼能retreive該元素以編輯它的輸入? 元素的名稱部分是否是對控制器的引用(即pageFlow)時有可能嗎?

如果我想取回20%確定了以下元素....

我試圖讓一個使用XPath和cssSelector沒有運氣。 有什麼建議嗎?

+1

「// tr/td [@ class ='non-sortable-table'] [2]/span」 – faramka 2012-03-15 13:53:36

回答

2

它看起來像我可能想要在XPath或CSS中使用啓動類型運算符。

喜歡的東西:

XPath: //input[starts-with(@name, 'plate_order')] 
CSS: input[name^='plate_order'] 

類似的事情應該適用於跨度,太(如果你知道文):

XPath: //span[starts-with(., '20%')] 
CSS/Sizzle*: span:contains('20%') 

如果你不知道的文字,然後這個東西xpath可能工作。

XPath: //input[starts-with(@name, 'plate_order]/../../td/span 

* 包含函數不是純CSS。這是Sizzle圖書館提供的補充。這可能會或可能不會工作,具體取決於Selenium是使用內置CSS庫還是注入Sizzle。

+0

優雅,開始 - 正是我在這裏所需要的。不過,我選擇使用String [] elements = driver.findElement(By.xpath(「// table/tbody」))。getText().split(「\\ n」);'因爲它是一個getText只會返回表tbody中每個元素的字符串。然後,我使用每一行來標識所下的訂單。 – 2012-03-16 15:13:49

+0

Andy Tinkham的回答涵蓋了xpath寫得很好。謝謝安迪。當沒有標籤的id或名稱時,我已經學會了如何編寫xpath。 // span [starts-with(。,'20%')]:這對我很有幫助 – 2012-08-14 04:52:08

4

要從一個JavaScript結果返回一個元素,可以使用以下語法(我用jQuery的作爲簡化):

RenderedWebElement webElement = (RenderedWebElement) ((JavascriptExecutor) webDriver).executeScript("return jQuery('input[name^=plate_order]').get(0);"); 

還可以傳遞其previosly在硒中選擇的元素:

((JavascriptExecutor) webDriver).executeScript("return doSomethingWithElement(arguments[0]);", webElement); 
相關問題