Home Ask Login Register

Developers Planet

Your answer is one click away!

Er Vipin Singh February 2016

How to scrap the text of <li> and children

I am trying to scrape the content of <li> tags and within them.

The HTML looks like:

 <div class="insurancesAccepted">
   <h4>What insurance does he accept?*</h4>
   <ul class="noBottomMargin">
      <li class="first"><span>Aetna</span></li>
         <a title="See accepted plans" class="insurancePlanToggle arrowUp">AvMed</a>
         <ul style="display: block;" class="insurancePlanList">
            <li class="last first">Open Access</li>
         <a title="See accepted plans" class="insurancePlanToggle arrowUp">Blue Cross Blue Shield</a>
         <ul style="display: block;" class="insurancePlanList">
            <li class="last first">Blue Card PPO</li>
         <a title="See accepted plans" class="insurancePlanToggle arrowUp">Cigna</a>
         <ul style="display: block;" class="insurancePlanList">
            <li class="first">Cigna HMO</li>
            <li>Cigna PPO</li>
            <li class="last">Great West Healthcare-Cigna PPO</li>
      <li class="last">
         <a title="See accepted plans" class="insurancePlanToggle arrowUp">Empire Blue Cross Blue Shield</a>
         <ul style="display: block;" class="insurancePlanList">
            <li class="last first">Empire Blue Cross Blue Shield HMO</li>

The main issue is when I am trying to get content from:

doc.css('.insurancesAccepted li').text.strip

It displays all <li> text at once. I want "AvMed" and "Open Access" scrapped at the same time with a relationship paramete


mudasobwa February 2016

The problem is that doc.css('.insurancesAccepted li') matches all nested list items, not only direct descendants. To match only a direct descendant one should use a parent > child CSS rule. To accomplish your task you need to carefully assemble the result of the iteration:

doc = Nokogiri::HTML(html)
result = doc.css('div.insurancesAccepted > ul > li').each do |li|
  chapter = li.css('span').text.strip
  section = li.css('a').text.strip
  subsections = li.css('ul > li').map(&:text).map(&:strip)

  puts "#{chapter} ⇒ [ #{section} ⇒ [ #{subsections.join(', ')} ] ]"
  puts '=' * 40

Resulted in:

# Aetna ⇒ [  ⇒ [  ] ]
# ========================================
#  ⇒ [ AvMed ⇒ [ Open Access ] ]
# ========================================
#  ⇒ [ Blue Cross Blue Shield ⇒ [ Blue Card PPO ] ]
# ========================================
#  ⇒ [ Cigna ⇒ [ Cigna HMO, Cigna PPO, Great West Healthcare-Cigna PPO ] ]
# ========================================
#  ⇒ [ Empire Blue Cross Blue Shield ⇒ [ Empire Blue Cross Blue Shield HMO ] ]
# ========================================

Post Status

Asked in February 2016
Viewed 1,811 times
Voted 6
Answered 1 times


Leave an answer

Quote of the day: live life