user2572510
user2572510

Reputation: 233

How to get value from a placeholder using xpath

All of the elements are dynamic. I can see only Placeholder which is unique from the following html:-

<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;"
/>

I need to get the value displayed in

placeholder="Gender". 

I tried using

//input[@placeholder='Gender']

But my webdriver script failed to identify it.

Can anyone please help me out with possible solution to it?

Upvotes: 15

Views: 84669

Answers (4)

Vivek Nair
Vivek Nair

Reputation: 1

The best way is to find the element with CSS selector in this case - input[placeholder='Gender'], which can easily find the element.

Upvotes: 0

kiran
kiran

Reputation: 292

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

To get an attribute for a filed, you can use the .getAttribute() method.

Upvotes: 19

user3487861
user3487861

Reputation: 350

Try

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

Let me know is the above statement is working or not.

Upvotes: 0

Karthikeyan
Karthikeyan

Reputation: 2724

I assume you are dealing with (front end)script generated web elements, then you must need to embrace lean way of thinking. Don't try to pull out a web element by it's property alone. If you are not getting them try to build a xpath from its parent or siblings.

say, the HTML goes like this,

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

Then you can build a xpath as ,

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

for the HTML,

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

the xpath is ,

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

similarly there are n number of option available. Give them a try

Upvotes: 1

Related Questions