0

Here is my code so far. Which gathers all of the data into a WebElement and then adds it into an ArrayList.

protected List<String> getDates() {
    List<WebElement> DateElements = driver.findElements(By.xpath("//div[@class='dates']"));
    List<String> DateList = new ArrayList<String>();
    for (WebElement element : DateElements ) {
        DateList.add(element.getText());
    }

    return DateList;

However, my list contains text and a date separated by a comma (ex. text, text, date). I only want the date added to the ArrayList and not the text. How can I split only the date from the WebElement and add it to the ArrayList.

3
  • Can you give the example of what element.getText() returns? what is the format of date?
    – Alexey R.
    Jul 24 '18 at 13:26
  • It returns [Text, Text, 07/23/2018]. It does this 8 times each line having different text and different dates all in the same format.
    – user33922
    Jul 24 '18 at 13:34
  • Can you try using Regular Expressions in your code. Regular expression is a pattern matching concept which is applicable only to string class.By using this concept we can separate numeric and alphabets.
    – shanila
    Jul 24 '18 at 13:40
2

This code should work for you

protected List<String> getDates() {

  List<WebElement> DateElements = driver.findElements(By.xpath("//div[@class='dates']"));
  List<String> DateList = new ArrayList<String>();

  for (WebElement element : DateElements ) {
      String dateParsed[] = element.getText().split(",");
      if(dateParsed.length == 3){
          DateList.add(dateParsed[2].trim());
      }
  }

  return DateList;
}

Here you split the value that returns your element.getText() using comma separator. Then you make sure you have the proper splitting (you should have 3 elements). After that you just get the 3rd element and trim the value to get rid of leading and trailing white-spaces.

Array size checking is required. Otherwise you might face the exception when you will try to take the value by the index that does not exist.

1
  • Yay, this worked for me... Thank you so much for your help!!!
    – user33922
    Jul 24 '18 at 13:46
0

you would need to take the output of element.getText() and do a split on it to get the text and date separately.

Whilst its tempting to do something like this

element.getText().split(delimiter)[1] 

its better to be cautious and not assume to much about the form of the data so do it in steps so you can catch errors better incase the tag isn't well formed or the delimiter changes or the text is removed.

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.