Nikhil Oberoi
Nikhil Oberoi

Reputation: 1

How to get Text from H1 Tag which has no arguments in Web Driver?

<html>
  <head>...</head>
  <body>
    <h1>Phonetic Translator</h1>
    <br>
    <link rel="stylesheet" href="/style.css" type="text/css">
    <title>electRa Phonetic Translator</title>
    <p>Today's password is:</p>
    <h1>
      MQQJXJLCQZ
      <hr width="80%">
    </h1>
    <p>The phonetic translation is:</p>
    <h3>
      ...
    </h3>
    ...
  </body>
<html>

Hi,

I want to get the text MQQJXJLCQZ. As there are two H1 tags after Body. I have used XPath to get the text value but unfortunately I am getting the error message Type mismatch: cannot convert from String to WebElement

The code I have written is :

    String PasswordxPath = "/html/body/h1[2]/text()";
    WebElement H1Element = driver.findElement(By.xpath(PasswordxPath));
    WebElement getPassword = H1Element.getText();

Please, can someone correct this code or suggest another way to get the text Value ?

Thanks,

UPDATE1

I have used string to get the text value, but now i am unable to put this value in the form using sendKeys. Error log as below:

Element info: {Using=xpath, value=/html/body/h1[2]/text()} at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Nativ‌​‌​e Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknow‌​‌​n Source)

Upvotes: 0

Views: 3294

Answers (3)

david_c
david_c

Reputation: 227

I had a similar problem where getText() wasn't working. Try using getAttribute("innerHTML")

Upvotes: 1

murali selenium
murali selenium

Reputation: 3927

As said, here is the problem

  WebElement getPassword = H1Element.getText();

getText() returns the String value but not WebElement. So you need to use String here, like

   String getPassword = H1Element.getText();

Upvotes: 0

S&#233;bastien Temprado
S&#233;bastien Temprado

Reputation: 1463

Replace WebElement by String in the last line :

String PasswordxPath = "/html/body/h1[2]/text()";
WebElement H1Element = driver.findElement(By.xpath(PasswordxPath));
String getPassword = H1Element.getText();

Upvotes: 0

Related Questions