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
.
the_coder
7541 gold badge4 silver badges13 bronze badges
asked Mar 24, 2017 at 12:29
-
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.Peter M. - stands for Monica– Peter M. - stands for Monica2017年03月24日 13:59:47 +00:00Commented 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– Sushant2017年03月24日 14:25:35 +00:00Commented Mar 24, 2017 at 14:25
-
2Exactly. So you DON'T want to convert element to string but elem.getText() of it.Peter M. - stands for Monica– Peter M. - stands for Monica2017年03月24日 15:13:30 +00:00Commented Mar 24, 2017 at 15:13
-
Yeah. But how to do that?Sushant– Sushant2017年03月24日 15:15:37 +00:00Commented Mar 24, 2017 at 15:15
3 Answers 3
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++;
}
answered Mar 24, 2017 at 12:44
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.
answered Mar 24, 2017 at 16:53
@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());
}
default