1

I am not able to convert webelement to string values.

 List<WebElement> a=driver.findElements(By.xpath("//*[@id='content']/table/tbody/tr/td[2]"));

i want convert above List<WebElement> to String.

4
  • What are you trying to accomplish? It does not make sense to convert object to a string. What you probably want is to access some of the attributes of the object which are strings, like text and/or value. Mar 24, 2017 at 13:59
  • Actually i want to getText from webelement and write that text into excel. That's why want to convert webelement into string so that i will able to write into excel.
    – Sushant
    Mar 24, 2017 at 14:25
  • 2
    Exactly. So you DON'T want to convert element to string but elem.getText() of it. Mar 24, 2017 at 15:13
  • Yeah. But how to do that?
    – Sushant
    Mar 24, 2017 at 15:15

3 Answers 3

4

You can do something like the following:

List<WebElement> links =driver.findElements(By.xpath("//*[@id='content']/table/tbody/tr/td[2]"));

String []linkText =new String[links.size()];
int i=0;

//Storing List elements text into String array
for(WebElement a: links)
{
   linkText[i]=a.getText();
   i++;
}
0

Here's another way you can do it using java 8 features:

By byXpath = By.xpath("//*[@id='content']/table/tbody/tr/td[2]");
List<WebElement> links = driver.findElements(byXpath);

List<String> texts = links.stream().map(WebElement::getText).collect(Collectors.toList());

This will iterate through each WebElement, call getText, and collect all the returned values into a brand new list.

0
    @FindBys({
        @FindBy(xpath = "//div[@class=\"error-text text--center margin--bottom_10\"]")
})
private List<WebElement> errorTexts;

  private List<String> getAllErrorsText() {
    return errorTexts.stream()
            .map(WebElement::getText)
            .collect(Collectors.toList());
}

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.