I am trying this:

String str = "//*[@id="Result"]/h2";
WebElement vele = driver.findElement(By.cssSelector(str));
String vin = vele.toString();
System.out.println("Vin is"+vin);

The result is:

[[FirefoxDriver: firefox on WINDOWS (dcb60bbf-03e4-40df-8985-fbb35a988add)] -> css selector: #Result > h2]

I should get result as:


My HTML code is:

<script language="javascript">window.onload = showLoad('random', 'random');</script>
<form method="post" action="" name="input">
<div id="container">
<input id="button" class="random" type="button" value="Generate Random VIN" onclick="showResult('random', 'random')" name="mk_vin"/>
<span id="Result">
<input id="vin" class="verifybox" type="text" maxlength="17" value="" name="vin"/>
<input id="button" type="button" value="Verify VIN" onclick="showResult('verify', document.getElementById('vin').value)" name="ck_vin"/>
<div id="about">
<div id="footer" style="display: none;">
  • Please format your post properly. Also, your HTML code is missing.
    – FDM
    Apr 15, 2015 at 17:31

2 Answers 2

  1. Why use XPath in your CSS selector? Just try this (assuming your selector is correct for the page you want to test).

WebElement vele = driver.findElement(By.cssSelector("#Result h2"));

  1. You need to get the text of the WebElement. What you're doing is converting the webElement object to its string representation. Use this method instead:

System.out.println("Vin is " + vele.getText());

See also the documentation here.


Hey there's two issues here:

A) you're calling ToString on an IWebElement. Try calling vele.Text instead of vele.ToString() instead. This will get you the text of the element rather than a taxi representation of the IWebElement.

B) you're using an xpath selector, but you're telling Webdriver that you want to use css selector to locate the element. You can use By.XPath with the code you have instead, the xpath you have written (str) is valid and should match ok.

  • CssSelector is preferred over XPath though.
    – FDM
    Apr 16, 2015 at 5:17
  • 1
    The you could write the css selector span#Result h2
    – chrisc
    Apr 16, 2015 at 7:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.