Class: Readability::Document
- Inherits:
-
Object
- Object
- Readability::Document
- Defined in:
- lib/readability.rb
Constant Summary collapse
- DEFAULT_OPTIONS =
{ :retry_length => 250, :min_text_length => 25, :remove_unlikely_candidates => true, :weight_classes => true, :clean_conditionally => true, :remove_empty_nodes => true, :min_image_width => 130, :min_image_height => 80, :ignore_image_format => [] }.freeze
- REGEXES =
{ :unlikelyCandidatesRe => /combx|comment|community|disqus|extra|foot|header|menu|remark|rss|shoutbox|sidebar|sponsor|ad-break|agegate|pagination|pager|popup/i, :okMaybeItsACandidateRe => /and|article|body|column|main|shadow/i, :positiveRe => /article|body|content|entry|hentry|main|page|pagination|post|text|blog|story/i, :negativeRe => /combx|comment|com-|contact|foot|footer|footnote|masthead|media|meta|outbrain|promo|related|scroll|shoutbox|sidebar|sponsor|shopping|tags|tool|widget/i, :divToPElementsRe => /<(a|blockquote|dl|div|img|ol|p|pre|table|ul)/i, :replaceBrsRe => /(<br[^>]*>[ \n\r\t]*){2,}/i, :replaceFontsRe => /<(\/?)font[^>]*>/i, :trimRe => /^\s+|\s+$/, :normalizeRe => /\s{2,}/, :killBreaksRe => /(<br\s*\/?>(\s| ?)*){1,}/, :videoRe => /http:\/\/(www\.)?(youtube|vimeo)\.com/i }
Instance Attribute Summary collapse
-
#best_candidate ⇒ Object
Returns the value of attribute best_candidate.
-
#best_candidate_has_image ⇒ Object
Returns the value of attribute best_candidate_has_image.
-
#candidates ⇒ Object
Returns the value of attribute candidates.
-
#html ⇒ Object
Returns the value of attribute html.
-
#options ⇒ Object
Returns the value of attribute options.
Instance Method Summary collapse
- #class_weight(e) ⇒ Object
- #clean_conditionally(node, candidates, selector) ⇒ Object
- #content(remove_unlikely_candidates = :default) ⇒ Object
- #debug(str) ⇒ Object
- #get_article(candidates, best_candidate) ⇒ Object
- #get_link_density(elem) ⇒ Object
- #image_meets_criteria?(image) ⇒ Boolean
- #images(content = nil, reload = false) ⇒ Object
-
#initialize(input, options = {}) ⇒ Document
constructor
A new instance of Document.
- #load_image(url) ⇒ Object
- #make_html ⇒ Object
- #prepare_candidates ⇒ Object
- #remove_unlikely_candidates! ⇒ Object
- #sanitize(node, candidates, options = {}) ⇒ Object
- #score_node(elem) ⇒ Object
- #score_paragraphs(min_text_length) ⇒ Object
- #select_best_candidate(candidates) ⇒ Object
- #title ⇒ Object
- #transform_misused_divs_into_paragraphs! ⇒ Object
Constructor Details
#initialize(input, options = {}) ⇒ Document
Returns a new instance of Document.
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
# File 'lib/readability.rb', line 21 def initialize(input, = {}) @options = DEFAULT_OPTIONS.merge() @input = input if RUBY_VERSION =~ /^1\.9\./ && !@options[:encoding] @input = GuessHtmlEncoding.encode(@input, @options[:html_headers]) unless @options[:do_not_guess_encoding] @options[:encoding] = @input.encoding.to_s end @input = @input.gsub(REGEXES[:replaceBrsRe], '</p><p>').gsub(REGEXES[:replaceFontsRe], '<\1span>') @remove_unlikely_candidates = @options[:remove_unlikely_candidates] @weight_classes = @options[:weight_classes] @clean_conditionally = @options[:clean_conditionally] @best_candidate_has_image = true make_html end |
Instance Attribute Details
#best_candidate ⇒ Object
Returns the value of attribute best_candidate.
19 20 21 |
# File 'lib/readability.rb', line 19 def best_candidate @best_candidate end |
#best_candidate_has_image ⇒ Object
Returns the value of attribute best_candidate_has_image.
19 20 21 |
# File 'lib/readability.rb', line 19 def best_candidate_has_image @best_candidate_has_image end |
#candidates ⇒ Object
Returns the value of attribute candidates.
19 20 21 |
# File 'lib/readability.rb', line 19 def candidates @candidates end |
#html ⇒ Object
Returns the value of attribute html.
19 20 21 |
# File 'lib/readability.rb', line 19 def html @html end |
#options ⇒ Object
Returns the value of attribute options.
19 20 21 |
# File 'lib/readability.rb', line 19 def @options end |
Instance Method Details
#class_weight(e) ⇒ Object
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 |
# File 'lib/readability.rb', line 243 def class_weight(e) weight = 0 return weight unless @weight_classes if e[:class] && e[:class] != "" if e[:class] =~ REGEXES[:negativeRe] weight -= 25 end if e[:class] =~ REGEXES[:positiveRe] weight += 25 end end if e[:id] && e[:id] != "" if e[:id] =~ REGEXES[:negativeRe] weight -= 25 end if e[:id] =~ REGEXES[:positiveRe] weight += 25 end end weight end |
#clean_conditionally(node, candidates, selector) ⇒ Object
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 |
# File 'lib/readability.rb', line 370 def clean_conditionally(node, candidates, selector) return unless @clean_conditionally node.css(selector).each do |el| weight = class_weight(el) content_score = candidates[el] ? candidates[el][:content_score] : 0 name = el.name.downcase if weight + content_score < 0 el.remove debug("Conditionally cleaned #{name}##{el[:id]}.#{el[:class]} with weight #{weight} and content score #{content_score} because score + content score was less than zero.") elsif el.text.count(",") < 10 counts = %w[p img li a embed input].inject({}) { |m, kind| m[kind] = el.css(kind).length; m } counts["li"] -= 100 content_length = el.text.strip.length # Count the text length excluding any surrounding whitespace link_density = get_link_density(el) to_remove = false reason = "" if counts["img"] > counts["p"] reason = "too many images" to_remove = true elsif counts["li"] > counts["p"] && name != "ul" && name != "ol" reason = "more <li>s than <p>s" to_remove = true elsif counts["input"] > (counts["p"] / 3).to_i reason = "less than 3x <p>s than <input>s" to_remove = true elsif content_length < ([:min_text_length] || TEXT_LENGTH_THRESHOLD) && (counts["img"] == 0 || counts["img"] > 2) reason = "too short a content length without a single image" to_remove = true elsif weight < 25 && link_density > 0.2 reason = "too many links for its weight (#{weight})" to_remove = true elsif weight >= 25 && link_density > 0.5 reason = "too many links for its weight (#{weight})" to_remove = true elsif (counts["embed"] == 1 && content_length < 75) || counts["embed"] > 1 reason = "<embed>s with too short a content length, or too many <embed>s" to_remove = true end if to_remove debug("Conditionally cleaned #{name}##{el[:id]}.#{el[:class]} with weight #{weight} and content score #{content_score} because it has #{reason}.") el.remove end end end end |
#content(remove_unlikely_candidates = :default) ⇒ Object
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 |
# File 'lib/readability.rb', line 134 def content(remove_unlikely_candidates = :default) @remove_unlikely_candidates = false if remove_unlikely_candidates == false prepare_candidates article = get_article(@candidates, @best_candidate) cleaned_article = sanitize(article, @candidates, ) if article.text.strip.length < [:retry_length] if @remove_unlikely_candidates @remove_unlikely_candidates = false elsif @weight_classes @weight_classes = false elsif @clean_conditionally @clean_conditionally = false else # nothing we can do return cleaned_article end make_html content else cleaned_article end end |
#debug(str) ⇒ Object
285 286 287 |
# File 'lib/readability.rb', line 285 def debug(str) puts str if [:debug] end |
#get_article(candidates, best_candidate) ⇒ Object
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 |
# File 'lib/readability.rb', line 160 def get_article(candidates, best_candidate) # Now that we have the top candidate, look through its siblings for content that might also be related. # Things like preambles, content split by ads that we removed, etc. sibling_score_threshold = [10, best_candidate[:content_score] * 0.2].max output = Nokogiri::XML::Node.new('div', @html) best_candidate[:elem].parent.children.each do |sibling| append = false append = true if sibling == best_candidate[:elem] append = true if candidates[sibling] && candidates[sibling][:content_score] >= sibling_score_threshold if sibling.name.downcase == "p" link_density = get_link_density(sibling) node_content = sibling.text node_length = node_content.length if node_length > 80 && link_density < 0.25 append = true elsif node_length < 80 && link_density == 0 && node_content =~ /\.( |$)/ append = true end end if append sibling_dup = sibling.dup # otherwise the state of the document in processing will change, thus creating side effects sibling_dup.name = "div" unless %w[div p].include?(sibling.name.downcase) output << sibling_dup end end output end |
#get_link_density(elem) ⇒ Object
207 208 209 210 211 |
# File 'lib/readability.rb', line 207 def get_link_density(elem) link_length = elem.css("a").map(&:text).join("").length text_length = elem.text.length link_length / text_length.to_f end |
#image_meets_criteria?(image) ⇒ Boolean
110 111 112 113 |
# File 'lib/readability.rb', line 110 def image_meets_criteria?(image) return false if [:ignore_image_format].include?(image[:format].downcase) image[:width] >= ([:min_image_width] || 0) && image[:height] >= ([:min_image_height] || 0) end |
#images(content = nil, reload = false) ⇒ Object
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 |
# File 'lib/readability.rb', line 56 def images(content=nil, reload=false) begin require 'mini_magick' rescue LoadError raise "Please install mini_magick in order to use the #images feature." end @best_candidate_has_image = false if reload prepare_candidates list_images = [] tested_images = [] content = @best_candidate[:elem] unless reload return list_images if content.nil? elements = content.css("img").map(&:attributes) elements.each do |element| next unless element["src"] url = element["src"].value height = element["height"].nil? ? 0 : element["height"].value.to_i width = element["width"].nil? ? 0 : element["width"].value.to_i format = File.extname(url).gsub(".", "") image = {:width => width, :height => height, :format => format} image = load_image(url) if url =~ /\Ahttps?:\/\//i && (height.zero? || width.zero?) next unless image if tested_images.include?(url) debug("Image was tested: #{url}") next end tested_images.push(url) if image_meets_criteria?(image) list_images << url else debug("Image discarded: #{url} - height: #{image[:height]} - width: #{image[:width]} - format: #{image[:format]}") end end (list_images.empty? and content != @html) ? images(@html, true) : list_images end |
#load_image(url) ⇒ Object
101 102 103 104 105 106 107 108 |
# File 'lib/readability.rb', line 101 def load_image(url) begin MiniMagick::Image.open(url) rescue => e debug("Image error: #{e}") nil end end |
#make_html ⇒ Object
47 48 49 50 51 52 53 54 |
# File 'lib/readability.rb', line 47 def make_html @html = Nokogiri::HTML(@input, nil, @options[:encoding]) # In case document has no body, such as from empty string or redirect @html = Nokogiri::HTML('<body />', nil, @options[:encoding]) if @html.css('body').length == 0 # Remove html comment tags @html.xpath('//comment()').each { |i| i.remove } end |
#prepare_candidates ⇒ Object
38 39 40 41 42 43 44 45 |
# File 'lib/readability.rb', line 38 def prepare_candidates @html.css("script, style").each { |i| i.remove } remove_unlikely_candidates! if @remove_unlikely_candidates transform_misused_divs_into_paragraphs! @candidates = score_paragraphs([:min_text_length]) @best_candidate = select_best_candidate(@candidates) end |
#remove_unlikely_candidates! ⇒ Object
289 290 291 292 293 294 295 296 297 |
# File 'lib/readability.rb', line 289 def remove_unlikely_candidates! @html.css("*").each do |elem| str = "#{elem[:class]}#{elem[:id]}" if str =~ REGEXES[:unlikelyCandidatesRe] && str !~ REGEXES[:okMaybeItsACandidateRe] && (elem.name.downcase != 'html') && (elem.name.downcase != 'body') debug("Removing unlikely candidate - #{str}") elem.remove end end end |
#sanitize(node, candidates, options = {}) ⇒ Object
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 |
# File 'lib/readability.rb', line 319 def sanitize(node, candidates, = {}) node.css("h1, h2, h3, h4, h5, h6").each do |header| header.remove if class_weight(header) < 0 || get_link_density(header) > 0.33 end node.css("form, object, iframe, embed").each do |elem| elem.remove end if @options[:remove_empty_nodes] # remove <p> tags that have no text content - this will also remove p tags that contain only images. node.css("p").each do |elem| elem.remove if elem.content.strip.empty? end end # Conditionally clean <table>s, <ul>s, and <div>s clean_conditionally(node, candidates, "table, ul, div") # We'll sanitize all elements using a whitelist base_whitelist = @options[:tags] || %w[div p] # We'll add whitespace instead of block elements, # so a<br>b will have a nice space between them base_replace_with_whitespace = %w[br hr h1 h2 h3 h4 h5 h6 dl dd ol li ul address blockquote center] # Use a hash for speed (don't want to make a million calls to include?) whitelist = Hash.new base_whitelist.each {|tag| whitelist[tag] = true } replace_with_whitespace = Hash.new base_replace_with_whitespace.each { |tag| replace_with_whitespace[tag] = true } ([node] + node.css("*")).each do |el| # If element is in whitelist, delete all its attributes if whitelist[el.node_name] el.attributes.each { |a, x| el.delete(a) unless @options[:attributes] && @options[:attributes].include?(a.to_s) } # Otherwise, replace the element with its contents else if replace_with_whitespace[el.node_name] el.swap(Nokogiri::XML::Text.new(' ' << el.text << ' ', el.document)) else el.swap(Nokogiri::XML::Text.new(el.text, el.document)) end end end # Get rid of duplicate whitespace node.to_html.gsub(/[\r\n\f]+/, "\n" ).gsub(/[\t ]+/, " ") end |
#score_node(elem) ⇒ Object
270 271 272 273 274 275 276 277 278 279 280 281 282 283 |
# File 'lib/readability.rb', line 270 def score_node(elem) content_score = class_weight(elem) case elem.name.downcase when "div" content_score += 5 when "blockquote" content_score += 3 when "form" content_score -= 3 when "th" content_score -= 5 end { :content_score => content_score, :elem => elem } end |
#score_paragraphs(min_text_length) ⇒ Object
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 |
# File 'lib/readability.rb', line 213 def score_paragraphs(min_text_length) candidates = {} @html.css("p,td").each do |elem| parent_node = elem.parent grand_parent_node = parent_node.respond_to?(:parent) ? parent_node.parent : nil inner_text = elem.text # If this paragraph is less than 25 characters, don't even count it. next if inner_text.length < min_text_length candidates[parent_node] ||= score_node(parent_node) candidates[grand_parent_node] ||= score_node(grand_parent_node) if grand_parent_node content_score = 1 content_score += inner_text.split(',').length content_score += [(inner_text.length / 100).to_i, 3].min candidates[parent_node][:content_score] += content_score candidates[grand_parent_node][:content_score] += content_score / 2.0 if grand_parent_node end # Scale the final candidates score based on link density. Good content should have a # relatively small link density (5% or less) and be mostly unaffected by this operation. candidates.each do |elem, candidate| candidate[:content_score] = candidate[:content_score] * (1 - get_link_density(elem)) end candidates end |
#select_best_candidate(candidates) ⇒ Object
193 194 195 196 197 198 199 200 201 202 203 204 205 |
# File 'lib/readability.rb', line 193 def select_best_candidate(candidates) sorted_candidates = candidates.values.sort { |a, b| b[:content_score] <=> a[:content_score] } debug("Top 5 candidates:") sorted_candidates[0...5].each do |candidate| debug("Candidate #{candidate[:elem].name}##{candidate[:elem][:id]}.#{candidate[:elem][:class]} with score #{candidate[:content_score]}") end best_candidate = sorted_candidates.first || { :elem => @html.css("body").first, :content_score => 0 } debug("Best candidate #{best_candidate[:elem].name}##{best_candidate[:elem][:id]}.#{best_candidate[:elem][:class]} with score #{best_candidate[:content_score]}") best_candidate end |
#title ⇒ Object
129 130 131 132 |
# File 'lib/readability.rb', line 129 def title title = @html.css("title").first title ? title.text : nil end |
#transform_misused_divs_into_paragraphs! ⇒ Object
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 |
# File 'lib/readability.rb', line 299 def transform_misused_divs_into_paragraphs! @html.css("*").each do |elem| if elem.name.downcase == "div" # transform <div>s that do not contain other block elements into <p>s if elem.inner_html !~ REGEXES[:divToPElementsRe] debug("Altering div(##{elem[:id]}.#{elem[:class]}) to p"); elem.name = "p" end else # wrap text nodes in p tags # elem.children.each do |child| # if child.text? # debug("wrapping text node with a p") # child.swap("<p>#{child.text}</p>") # end # end end end end |