Raji
Raji

Reputation: 845

Get Text between two tags using nokogiri

My HTML structure is

<div class="line">
    <h2>Header</h2>
    <h3>Mailing Address</h3>
    2349 Glorem ipsun lorem ipsum  CA 95833<br>
    <br>    

    Phone: 111-111-2111&nbsp;&nbsp;&nbsp;&nbsp;Fax: 111-511-1111<br>
    <a onfocus="blur()" target="_blank&quot;" href="">some text</a><br>
    <a onfocus="blur()" target="_blank" href="">some address</a><br>
    <div><p></p></div>      

    <h3>Contact(s)</h3>
</div>

The HTML page contains several <div class=line></div> elements. For each div i need to extract Phone and Fax in a array with other data. I tried using

doc.css("div#ctl00_cphContent_divBrowseByMember").each do |div|
  div.css("div.line").each do |line|
    line.xpath('//text()[preceding-sibling::br and following-sibling::a]').text.strip
  end
end

It returns nothing and returns time out error. If I try as line.xpath('//text()[preceding-sibling::br and following-sibling::a]')[0].text.strip will return same Phone and fax for all other divs. Please suggest any other solution that will help me.

Upvotes: 0

Views: 926

Answers (1)

pguardiario
pguardiario

Reputation: 54984

The easy way:

phone, fax = line.text.scan /\d{3}-\d{3}-\d{4}/

Upvotes: 3

Related Questions