user2950593 user2950593 - 5 months ago 7x
Ruby Question

How to get text from <li> elements

I have:

<li>text2 </li>

Right now I get the text from
like this:

result = page.css(' ul li').text

The problem is, as a result I get a string with no spaces like


I want it to be divided with
, like

How do I do this?


From "Searching a XML/HTML Document" :

methods xpath and css actually return a NodeSet, which acts very much like an array, and contains matching nodes from the document.

So, if you want to concatenate all texts from all <li> tags, then you should work with the css method result as with a collection:

page.css('ul li') # selects all li tags and returns collection of Node objects
    .map(&:text) # maps collection of li nodes into array of corresponding texts
    .join('<br>') # concatenates all nodes texts into a single string with <br> separator