user2457894
user2457894

Reputation: 141

Selenium WebDriver findElement(By.xpath()) not working for me

I've been through the xpath tutorials and checked many other posts, hence I'm not sure what I'm missing. I'm simply trying to find the following element by xpath:

<input class="t-TextBox" type="email" test-id="test-username"/>

I've tried many things, such as:

element = findElement(By.xpath("//[@test-id='test-username']"));

The error is Expression is not a legal expression.

I'm using Firefox on MacBook

Any suggestion would be greatly appreciated.

Upvotes: 12

Views: 142902

Answers (8)

Andrian Durlestean
Andrian Durlestean

Reputation: 1730

element = findElement(By.xpath("//*[@test-id='test-username']"));
element = findElement(By.xpath("//input[@test-id='test-username']"));

(*) - means any tag name.

Upvotes: 20

Juarez Lustosa
Juarez Lustosa

Reputation: 821

You can use contains too:

element = findElement(By.xpath("//input[contains (@test-id,"test-username")]");

Upvotes: 2

Umesh
Umesh

Reputation: 125

Just need to add * at the beginning of xpath and closing bracket at last.

element = findElement(By.xpath("//*[@test-id='test-username']"));

Upvotes: 2

Shivendra Pandey
Shivendra Pandey

Reputation: 423

Correct Xpath syntax is like:

//tagname[@value='name']

So you should write something like this:

findElement(By.xpath("//input[@test-id='test-username']"));

Upvotes: 1

Sitnikov M
Sitnikov M

Reputation: 21

You missed the closing parenthesis at the end:

element = findElement(By.xpath("//[@test-id='test-username']"));

Upvotes: 2

Arpan Buch
Arpan Buch

Reputation: 1400

your syntax is completely wrong....you need to give findelement to the driver

i.e your code will be :

WebDriver driver = new FirefoxDriver();
WebeElement element ;

element = driver.findElement(By.xpath("//[@test-id='test-username']"); 

// your xpath is: "//[@test-id='test-username']"

i suggest try this :"//*[@test-id='test-username']"

Upvotes: 3

Prash
Prash

Reputation: 39

You haven't specified what kind of html element you are trying to do an absolute xpath search on. In your case, it's the input element.

Try this:

element = findElement(By.xpath("//input[@class='t-TextBox' and @type='email' and @test-    
id='test-username']");

Upvotes: 1

leonhart
leonhart

Reputation: 1201

You should add the tag name in the xpath, like:

element = findElement(By.xpath("//input[@test-id='test-username']");

Upvotes: 4

Related Questions