├── .gitignore ├── .travis.yml ├── LICENSE.md ├── Makefile ├── README.md ├── index.js ├── lib └── utils.js ├── package.json └── test ├── article.js └── mocha.opts /.gitignore: -------------------------------------------------------------------------------- 1 | lib-cov 2 | *.seed 3 | *.log 4 | *.csv 5 | *.dat 6 | *.out 7 | *.pid 8 | *.gz 9 | 10 | pids 11 | logs 12 | results 13 | 14 | node_modules 15 | npm-debug.log 16 | 17 | # Coverage directory used by tools like istanbul 18 | coverage 19 | 20 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 21 | .grunt 22 | 23 | # Compiled binary addons (http://nodejs.org/api/addons.html) 24 | build/Release 25 | 26 | .idea -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - "5" 4 | - "4" 5 | - "0.12" 6 | - "0.11" 7 | - "0.10" 8 | - iojs 9 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | REPORTER = dot 2 | 3 | test: 4 | ./node_modules/.bin/mocha -R spec 5 | 6 | .PHONY: test -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![NPM](https://nodei.co/npm/node-read.png?downloads=true)](https://nodei.co/npm/node-read/) 2 | # Node-read 3 | 4 | Get Readable Content from any page. Based on Arc90's readability project. 5 | 6 | ## Features 7 | 8 | 1. Blazingly Fast. This project is based on Cheerio engine, which is 8x times faster than JSDOM. 9 | 10 | ## Why not Node-readability 11 | 12 | Before starting this project I used Node-readability, but the dependencies of that project plus the slowness of JSDOM made it very frustrating to work with. The compiling of contextify module (dependency of JSDOM) failed 9/10 times. And if you wanted to use node-readability with node-webkit you had to manually rebuild contextify with nw-gyp, which is not the optimal solution. 13 | 14 | So I decided to write my own version of Arc90's Readability using the fast Cheerio engine with the least number of dependencies. 15 | 16 | The Usage of this module is similiar to node-readability, so it's easy to switch. 17 | 18 | ## Install 19 | 20 | npm install node-read 21 | 22 | ## Usage 23 | 24 | `read(html [, options], callback)` 25 | 26 | Where 27 | 28 | * **html** url or html code. 29 | * **options** is an optional options object 30 | * **callback** is the callback to run - `callback(error, article, meta)` 31 | 32 | Example 33 | 34 | var read = require('node-read'); 35 | 36 | read('http://howtonode.org/really-simple-file-uploads', function(err, article, res) { 37 | 38 | // Main Article. 39 | console.log(article.content); 40 | 41 | // Title 42 | console.log(article.title); 43 | 44 | // HTML 45 | console.log(article.html); 46 | 47 | // DOM 48 | console.log(article.dom); 49 | 50 | }); 51 | 52 | ## TODO 53 | 54 | * Examples, Docs 55 | * Get Comments with articles 56 | * Get the Author of the article 57 | * Better removal of unnecessary nodes 58 | * Better scoring of content: 59 | - Based on siblings 60 | - Based on content length, common words 61 | - Link density, Image density, other common elements density 62 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | var utils = require('./lib/utils.js'); 2 | var req = require('fetch').fetchUrl; 3 | var url = require('url'); 4 | var cheerio = require('cheerio'); 5 | 6 | function Article(dom, options, uri) { 7 | this.$ = dom; // Will be modified in-place after analyzing 8 | this.originalDOM = dom; // Save the original DOM if the user needs it 9 | this.cache = {}; 10 | 11 | if (uri && typeof uri != "undefined") { 12 | this.base = uri.protocol + "//" + uri.hostname + uri.pathname; 13 | if (uri.port && uri.port != 80) this.base += ":" + uri.port; 14 | } else { 15 | this.base = false; 16 | } 17 | 18 | this.options = options; 19 | this.__defineGetter__('content', function() { 20 | return this.getContent(true); 21 | }); 22 | this.__defineGetter__('title', function() { 23 | return this.getTitle(true); 24 | }); 25 | this.__defineGetter__('html', function() { 26 | return this.getHTML(true); 27 | }); 28 | this.__defineGetter__('dom', function() { 29 | return this.getDOM(true); 30 | }); 31 | } 32 | 33 | Article.prototype.getContent = function() { 34 | if (typeof this.cache['article-content'] !== 'undefined') { 35 | return this.cache['article-content']; 36 | } 37 | var content = utils.extract(this.$, this.base, this.options).html(); 38 | 39 | return this.cache['article-content'] = content; 40 | } 41 | 42 | // Better Article Title Extraction. 43 | // Author Zihua Li https://github.com/luin/node-readability 44 | Article.prototype.getTitle = function() { 45 | if (typeof this.cache['article-title'] !== 'undefined') { 46 | return this.cache['article-title']; 47 | } 48 | 49 | // Prefer to pull the title from one of the class names known to hold 50 | // the article title (Instapaper conventions and 51 | // https://www.readability.com/developers/guidelines#publisher). 52 | var preferredTitle = this.$('.entry-title, .instapaper_title'); 53 | if (preferredTitle.length > 0) { 54 | return this.cache['article-title'] = preferredTitle.first().text().trim(); 55 | } 56 | 57 | var title = this.$('title').text(); 58 | var betterTitle; 59 | var commonSeparatingCharacters = [' | ', ' _ ', ' - ', '«', '»', '—']; 60 | 61 | var self = this; 62 | commonSeparatingCharacters.forEach(function(char) { 63 | var tmpArray = title.split(char); 64 | if (tmpArray.length > 1) { 65 | if (betterTitle) return self.cache['article-title'] = title; 66 | betterTitle = tmpArray[0].trim(); 67 | } 68 | }); 69 | 70 | if (betterTitle && betterTitle.length > 10) { 71 | return this.cache['article-title'] = betterTitle; 72 | } 73 | 74 | return this.cache['article-title'] = title.trim(); 75 | } 76 | 77 | Article.prototype.getDOM = function() { 78 | return this.originalDOM; 79 | } 80 | 81 | Article.prototype.getHTML = function() { 82 | return this.$.html(); 83 | } 84 | 85 | var read = module.exports = function(html, options, callback) { 86 | if (typeof options === 'function') { 87 | callback = options; 88 | options = { 89 | considerDIVs: true, 90 | nodesToRemove: 'meta,iframe,noscript,style,aside,object,script' 91 | }; 92 | } 93 | 94 | if (!html.match(/^\s*]*>[ \n\r\t]*){2,}/gi, 18 | replaceFontsRe: /<(\/?)font[^>]*>/gi, 19 | trimRe: /^\s+|\s+$/g, 20 | normalizeRe: /\s{2,}/g, 21 | killBreaksRe: /((\s| ?)*){1,}/g, 22 | videoRe: /http:\/\/(www\.)?(youtube|vimeo|youku|tudou|56|yinyuetai)\.com/i, 23 | nextLink: /(next|weiter|continue|>([^\|]|$)|»([^\|]|$))/i // Will be used to get the next Page of Article 24 | }; 25 | 26 | /** 27 | * Node Types and their classification 28 | **/ 29 | 30 | var nodeTypes = { 31 | 'mostPositive': ['div'], 32 | 'positive': ['pre', 'td', 'blockquote'], 33 | 'negative': ['address', 'ol', 'ul', 'dl', 'dd', 'dt', 'li'], 34 | 'mostNegative': ['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'th'] 35 | }; 36 | 37 | /** 38 | * Select the TopCandidate from all possible candidates 39 | **/ 40 | 41 | function getArticle(candidates, $, options) { 42 | var topCandidate = null; 43 | 44 | candidates.forEach(function(elem) { 45 | var linkDensity = getLinkDensity(elem, $); 46 | var score = elem.data('readabilityScore'); 47 | var siblings = elem.children('p').length; 48 | 49 | elem.data('readabilityScore', Math.min(2, Math.max(siblings, 1)) * score * (1 - linkDensity)); 50 | if (!topCandidate || elem.data('readabilityScore') > topCandidate.data('readabilityScore')) { 51 | topCandidate = elem; 52 | } 53 | }); 54 | /** 55 | * If we still have no top candidate, just use the body as a last resort. 56 | * Should not happen. 57 | **/ 58 | if (topCandidate === null) { 59 | return $('body'); 60 | } 61 | 62 | // Perhaps the topCandidate is the parent? 63 | var parent; 64 | if (!(parent = topCandidate.parent()) || parent.length == 0 || topCandidate.children('p').length > 5) { 65 | return filterCandidates(topCandidate, topCandidate.children(), $); 66 | } else { 67 | return filterCandidates(topCandidate, parent.children(), $); 68 | } 69 | } 70 | 71 | /** 72 | * Filter TopCandidate Siblings (Children) based on their Link Density, and readabilityScore 73 | * Append the nodes to articleContent 74 | **/ 75 | 76 | function filterCandidates(topCandidate, siblings, $) { 77 | var articleContent = $("
"); 78 | var siblingScoreThreshold = Math.max(10, topCandidate.data('readabilityScore') * 0.2); 79 | 80 | siblings.each(function(index, elem) { 81 | 82 | var node = $(this); 83 | var append = false; 84 | var type = node.get(0).name; 85 | var score = node.data('readabilityScore'); 86 | var children = siblings.contents().length; 87 | 88 | if (node.is(topCandidate) || score > siblingScoreThreshold) { 89 | append = true; 90 | } 91 | 92 | if (children > 0) { 93 | siblings.contents().each(function(index, elem) { 94 | if (elem.name == "img") append = true; 95 | }); 96 | } 97 | 98 | if (!append && (type == 'p' || type == 'ul' || type == 'blockquote' || type == 'pre' || type == 'h2')) { 99 | $(elem).find('a').each(function(index, elems) { 100 | if ($(elems).text().length > 1) return; 101 | if (elems.name == "a") $(elems).remove(); 102 | }); 103 | 104 | var linkDensity = getLinkDensity(node, $); 105 | var len = node.text().length; 106 | if (len < 3) return; 107 | 108 | if (len > 80 && linkDensity < 0.25) { 109 | append = true; 110 | } else if (len < 80 && linkDensity == 0 && node.text().replace(regexps.trimRe, "").length > 0) { 111 | append = true; 112 | } 113 | 114 | } 115 | if (append) { 116 | articleContent.append(node); 117 | } 118 | }); 119 | return articleContent; 120 | } 121 | 122 | /** 123 | * Traverse all Nodes and remove unlikely Candidates. 124 | **/ 125 | 126 | function getCandidates($, base, options) { 127 | 128 | // Removing unnecessary nodes 129 | $(options.nodesToRemove).remove(); 130 | 131 | // Candidates Array 132 | var candidates = []; 133 | 134 | // Iterate over all Nodes in body 135 | $('*', 'body').each(function(index, element) { 136 | var node = $(this); 137 | 138 | // If node is null, return, otherwise Illegal Access Error 139 | if (!node || node.length == 0) return; 140 | var nodeType = node.get(0).name; 141 | 142 | // Remove Unlikely Candidates 143 | var classAndID = (node.attr('class') || "") + (node.attr('id') || ""); 144 | if (classAndID.search(regexps.unlikelyCandidatesRe) !== -1 && classAndID.search(regexps.okMaybeItsACandidateRe) == -1) { 145 | return node.remove(); 146 | } 147 | 148 | // Remove Elements that have no children and have no content 149 | if (nodeType == "div" && node.children().length < 1 && node.text().trim().length < 1) { 150 | return node.remove(); 151 | } 152 | 153 | // Remove Style 154 | node.removeAttr('style'); 155 | 156 | // turn all divs that don't have children block level elements into p's 157 | if (nodeType === "div" && options.considerDIVs) { 158 | if (node.html().search(regexps.divToPElementsRe) === -1) { 159 | node.replaceWith('

' + node.html() + '

'); 160 | } else { 161 | node.contents().each(function(index, element) { 162 | var child = $(this), 163 | childEntity; 164 | if (!child || !(childEntity = child.get(0))) { 165 | return; 166 | } 167 | if (childEntity.type == 'text' && childEntity.data && childEntity.data.replace(regexps.trimRe, '').length > 1) { 168 | child.replaceWith('

' + childEntity.data + '

'); 169 | } 170 | }); 171 | } 172 | } 173 | 174 | // score paragraphs. 175 | if (nodeType == "p" || nodeType == "pre") { 176 | return calculateNodeScore(node, candidates); 177 | } 178 | 179 | // Resolve URLs 180 | if (base) { 181 | if (nodeType == "img" && typeof node.attr('src') != "undefined") { 182 | node.attr('src', url.resolve(base, node.attr('src'))); 183 | } 184 | if (nodeType == "a" && typeof node.attr('href') != "undefined") { 185 | node.attr('href', url.resolve(base, node.attr('href'))); 186 | } 187 | } 188 | 189 | // Clean the headers 190 | if (["h1", "h2", "h3", "h4", "h5", "h6"].indexOf(nodeType) !== -1) { 191 | var weight = getClassWeight(node, $); 192 | var density = getLinkDensity(node, $); 193 | if (weight < 0 || density > 0.3) { 194 | node.remove(); 195 | } 196 | } 197 | 198 | }); 199 | // calculate scores of `P`s that were turned from DIV by us. 200 | $('p.node-read-div2p', 'body').each(function() { 201 | calculateNodeScore($(this), candidates); 202 | }); 203 | 204 | return candidates; 205 | } 206 | 207 | /** 208 | * Give a score to each node based on the Content. 209 | * @param node 210 | * @param contentScore 211 | * @param candidates 212 | */ 213 | function scoreCandidate(node, contentScore, candidates) { 214 | var score; 215 | if (typeof node.data('readabilityScore') == "undefined") { 216 | score = initializeNode(node); 217 | candidates.push(node); 218 | } else { 219 | score = node.data('readabilityScore') || 0; 220 | } 221 | node.data('readabilityScore', score + contentScore) 222 | } 223 | 224 | /** 225 | * calculate score of specified node. 226 | * @param node 227 | * @param candidates 228 | */ 229 | function calculateNodeScore(node, candidates) { 230 | var txt = node.text(); 231 | var contentScore = 1; 232 | 233 | // Ignore too small nodes 234 | if (txt.length < 25) return; 235 | 236 | // Add points for any commas within this paragraph 237 | // support Chinese commas. 238 | var commas = txt.match(/[,,.。;;??、]/g); 239 | if (commas && commas.length) { 240 | contentScore += commas.length; 241 | } 242 | 243 | // For every 100 characters in this paragraph, add another point. Up to 3 points. 244 | contentScore += Math.min(Math.floor(txt.length / 100), 3); 245 | 246 | // Initialize Parent and Grandparent 247 | // First initialize the parent node with contentScore / 1, then grandParentNode with contentScore / 2 248 | var parent = node.parent(); 249 | 250 | if (parent && parent.length > 0) { 251 | scoreCandidate(parent, contentScore, candidates); 252 | var grandParent = parent.parent(); 253 | if (grandParent && grandParent.length > 0) { 254 | scoreCandidate(grandParent, contentScore / 2, candidates); 255 | } 256 | } 257 | } 258 | 259 | /** 260 | * Check the type of node, and get its Weight 261 | **/ 262 | 263 | function initializeNode(node) { 264 | if (!node || node.length == 0) return 0; 265 | var tag = node.get(0).name; 266 | if (nodeTypes['mostPositive'].indexOf(tag) >= 0) return 5 + getClassWeight(node); 267 | if (nodeTypes['positive'].indexOf(tag) >= 0) return 3 + getClassWeight(node); 268 | if (nodeTypes['negative'].indexOf(tag) >= 0) return -3 + getClassWeight(node); 269 | if (nodeTypes['mostNegative'].indexOf(tag) >= 0) return -5 + getClassWeight(node); 270 | return -1; 271 | } 272 | 273 | /** 274 | * Node Weight is calculated based on className and ID of the node. 275 | **/ 276 | 277 | function getClassWeight(node) { 278 | if (node == null || node.length == 0) return 0; 279 | var classAndID = (node.attr('class') || "") + (node.attr('id') || ""); 280 | var weight = 0; 281 | 282 | if (node.get(0).name == "article") weight += 25; 283 | if (classAndID.search(regexps.negativeRe) !== -1) weight -= 25; 284 | if (classAndID.search(regexps.positiveRe) !== -1) weight += 25; 285 | 286 | return weight; 287 | } 288 | 289 | /** 290 | * Get Link density of this node. 291 | * Total length of link text in this node divided by the total text of the node. 292 | * Relative links are not included. 293 | **/ 294 | 295 | function getLinkDensity(node, $) { 296 | var links = node.find('a'); 297 | var textLength = node.text().length; 298 | var linkLength = 0; 299 | 300 | links.each(function(index, elem) { 301 | var href = $(this).attr('href'); 302 | if (!href || (href.length > 0 && href[0] === '#')) return; 303 | linkLength += $(this).text().length; 304 | }); 305 | 306 | return (linkLength / textLength) || 0; 307 | } 308 | 309 | /** 310 | * Main method 311 | * If the first run does not succeed, try the body element; 312 | **/ 313 | 314 | module.exports.extract = function($, base, options) { 315 | var candidates = getCandidates($, base, options); 316 | article = getArticle(candidates, $, options); 317 | if (article.length < 1) { 318 | article = getArticle([$('body')], $, options) 319 | } 320 | return article; 321 | } 322 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "node-read", 3 | "version": "0.1.7", 4 | "author": { 5 | "name": "Vadim Kravcenko" 6 | }, 7 | "description": "Get Clean Reading Content from every web page", 8 | "homepage": "https://github.com/bndr/node-read", 9 | "dependencies": { 10 | "fetch": "*", 11 | "cheerio": "^0.19.0" 12 | }, 13 | "devDependencies": { 14 | "mocha": "*", 15 | "should": "*", 16 | "nock": "~0.27.1" 17 | }, 18 | "licenses": [{ 19 | "type": "Apache License 2.0", 20 | "url": "http://www.apache.org/licenses/LICENSE-2.0" 21 | }], 22 | "keywords": [ 23 | "readability", 24 | "readable", 25 | "scraper", 26 | "extract" 27 | ], 28 | "repository": { 29 | "type": "git", 30 | "url": "git://github.com/bndr/node-read.git" 31 | }, 32 | "scripts": { 33 | "test": "make test" 34 | }, 35 | "main": "index.js", 36 | "readme": "# Node-read\n\nGet Readable Content from any page. Based on Arc90's readability project.\n\n## Features\n\n1. Blazingly Fast. This project is based on Cheerio engine, which is 8x times faster than JSDOM.\n\n## Why not Node-readability\n\nBefore starting this project I used Node-readability, but the dependencies of that project plus the slowness of JSDOM made it very frustrating to work with. The compiling of contextify module (dependency of JSDOM) failed 9/10 times. And if you wanted to use node-readability with node-webkit you had to manually rebuild contextify with nw-gyp, which is not the optimal solution.\n\nSo I decided to write my own version of Arc90's Readability using the fast Cheerio engine with the least number of dependencies.\n\nThe Usage of this module is similiar to node-readability, so it's easy to switch.\n\n## Install\n\n npm install node-read\n \n## Usage\n\n`read(html [, options], callback)`\n\nWhere\n\n * **html** url or html code.\n * **options** is an optional options object\n * **callback** is the callback to run - `callback(error, article, meta)`\n\nExample\n\n var read = require('node-read');\n\n read('http://howtonode.org/really-simple-file-uploads', function(err, article, res) {\n \n // Main Article.\n console.log(article.content);\n \n // Title\n console.log(article.title);\n\n // HTML \n console.log(article.html);\n \n // DOM\n console.log(article.dom);\n \n });\n", 37 | "readmeFilename": "README.md", 38 | "bugs": { 39 | "url": "https://github.com/bndr/node-read/issues" 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /test/article.js: -------------------------------------------------------------------------------- 1 | var read = require('../index.js') 2 | 3 | describe("Readability Test suite", function() { 4 | it("should get the article Content and Title from URL", function(done) { 5 | read("http://www.theguardian.com/world/2014/apr/27/ukraine-kidnapped-observers-slavyansk-vyacheslav-ponomarev", function(err, article, res) { 6 | article.content.should.containEql("The rebels did not exhibit five members of Ukraine's armed forces captured at the same time on Friday"); 7 | article.title.should.containEql("Ukraine: kidnapped observers paraded by pro-Russian gunmen in Slavyansk"); 8 | done(); 9 | }); 10 | }); 11 | 12 | it("should get title from HTML", function(done) { 13 | read("Random TitleRandom BodyIncorrect Title

Preferred Title

Random BodyIncorrect Title

Preferred Title

Random Body