2013-12-20 72 views
6

所有元素都是動態的。我只能看到佔位符是從以下HTML獨特: -如何使用xpath從佔位符中獲取值

<input 
    id="ext-gen1617" 
    type="text" 
    size="20" 
    class="x-form-field x-form-text x-form-focus" 
    autocomplete="off" 
    aria-invalid="false" 
    placeholder="Gender" 
    data-errorqtip="" 
    role="textbox" 
    aria-describedby="combobox-1166-errorEl" 
    aria-required="true" 
    style="width: 78px;" 
/> 

我需要顯示在

placeholder="Gender". 

值我嘗試使用

//input[@placeholder='Gender'] 

但我的webdriver腳本未能識別它。

任何人都可以請幫助我解決這個問題嗎?

+0

你得到了什麼錯誤?司機是在正確的框架? – Karthikeyan

+0

org.openqa.selenium.NoSuchElementException:找不到xpath == // *的元素[@ placeholder ='Gender'] – user2572510

+0

這個錯誤有很多種可能性,如果你的情況不適合這裏http:// stackoverflow .com/questions/17677587 /無法找到元素與Xpath/17695301#17695301,然後讓我知道,我們可以進一步挖掘 – Karthikeyan

回答

3
String s=driver.findElement(By.xpath("//input[@placeholder='Gender']")).getAttribute("placeholder"); 
System.out.println(s); 

要獲取某個字段的屬性,可以使用.getAttribute()方法。

+0

我需要在Gender字段內單擊。我如何做到這一點,如果我使用getAttribute()將返回一個字符串不是webelement? – user2572510

+0

你的意思是你需要輸入一些性別字段值? – kiran

+0

在上面的代碼中你問我在代碼中顯示的值是什麼,所以我在我的代碼中打印了佔位符值 – kiran

0

我假設你正在處理(前端)腳本生成的網頁元素,那麼你必須擁抱精益的思維方式。不要試圖通過它的屬性獨自拉出Web元素。如果你沒有得到他們嘗試從其父母或兄弟姐妹建立一個xpath。

說了,HTML是這樣的,

<div id="somestatic id"> 
    <div id="xyz"> 
    <input name="dynamic one"/> 
    </div> 
</div> 

然後你就可以建立一個到XPath,

//*[@id='staticID']/div/input 

爲HTML,

<div id="staticID"></div> 
    <input name="dynamic one"/> 

的XPath是,

//*[@id='staticID']/following-sibling::input 

同樣有n個選項可用。給他們一個嘗試

0

嘗試

driver.findElement(
    By.cssSelector("input[id*='ext-gen']") 
).getAttribute("placeholder") 

讓我知道是上面的語句是否工作。