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>
  • Please format your post properly. Also, your HTML code is missing. – FDM Apr 15 '15 at 17:31
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.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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