1

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:

2G3AM51N6M2768439

My HTML code is:

<document>
<html>
<head>
<body>
<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">
<h2>2G3AM51N6M2768439</h2>
</span>
<hr/>
<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>
<div id="about">
<div id="footer" style="display: none;">
</form>
</body>
</html>
</document>
1
  • Please format your post properly. Also, your HTML code is missing.
    – FDM
    Commented Apr 15, 2015 at 17:31

2 Answers 2

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.

2

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.

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

Your Answer

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

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