Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

README.md 9.2 KiB

3 år sedan
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. <p align="center">
  2. <img src="https://raw.github.com/inikulin/parse5/master/logo.png" alt="parse5" />
  3. </p>
  4. [![Build Status](https://api.travis-ci.org/inikulin/parse5.svg)](https://travis-ci.org/inikulin/parse5)
  5. [![npm](https://img.shields.io/npm/v/parse5.svg)](https://www.npmjs.com/package/parse5)
  6. *WHATWG HTML5 specification-compliant, fast and ready for production HTML parsing/serialization toolset for Node and io.js.*
  7. I needed fast and ready for production HTML parser, which will parse HTML as a modern browser's parser.
  8. Existing solutions were either too slow or their output was too inaccurate. So, this is how parse5 was born.
  9. **Included tools:**
  10. * [Parser](#class-parser) - HTML to DOM-tree parser.
  11. * [SimpleApiParser](#class-simpleapiparser) - [SAX](http://en.wikipedia.org/wiki/Simple_API_for_XML)-style parser for HTML.
  12. * [Serializer](#class-serializer) - DOM-tree to HTML code serializer.
  13. ## Install
  14. ```
  15. $ npm install parse5
  16. ```
  17. ## Usage
  18. ```js
  19. var Parser = require('parse5').Parser;
  20. //Instantiate parser
  21. var parser = new Parser();
  22. //Then feed it with an HTML document
  23. var document = parser.parse('<!DOCTYPE html><html><head></head><body>Hi there!</body></html>')
  24. //Now let's parse HTML-snippet
  25. var fragment = parser.parseFragment('<title>Parse5 is &#102;&#117;&#99;&#107;ing awesome!</title><h1>42</h1>');
  26. ```
  27. ## Is it fast?
  28. Check out [this benchmark](https://github.com/inikulin/node-html-parser-bench).
  29. ```
  30. Starting benchmark. Fasten your seatbelts...
  31. html5 (https://github.com/aredridel/html5) x 0.18 ops/sec ±5.92% (5 runs sampled)
  32. htmlparser (https://github.com/tautologistics/node-htmlparser/) x 3.83 ops/sec ±42.43% (14 runs sampled)
  33. htmlparser2 (https://github.com/fb55/htmlparser2) x 4.05 ops/sec ±39.27% (15 runs sampled)
  34. parse5 (https://github.com/inikulin/parse5) x 3.04 ops/sec ±51.81% (13 runs sampled)
  35. Fastest is htmlparser2 (https://github.com/fb55/htmlparser2),parse5 (https://github.com/inikulin/parse5)
  36. ```
  37. So, parse5 is as fast as simple specification incompatible parsers and ~15-times(!) faster than the current specification compatible parser available for the node.
  38. ## API reference
  39. ### Enum: TreeAdapters
  40. Provides built-in tree adapters which can be passed as an optional argument to the `Parser` and `Serializer` constructors.
  41. #### &bull; TreeAdapters.default
  42. Default tree format for parse5.
  43. #### &bull; TreeAdapters.htmlparser2
  44. Quite popular [htmlparser2](https://github.com/fb55/htmlparser2) tree format (e.g. used in [cheerio](https://github.com/MatthewMueller/cheerio) and [jsdom](https://github.com/tmpvar/jsdom)).
  45. ---------------------------------------
  46. ### Class: Parser
  47. Provides HTML parsing functionality.
  48. #### &bull; Parser.ctor([treeAdapter, options])
  49. Creates new reusable instance of the `Parser`. Optional `treeAdapter` argument specifies resulting tree format. If `treeAdapter` argument is not specified, `default` tree adapter will be used.
  50. `options` object provides the parsing algorithm modifications:
  51. ##### options.decodeHtmlEntities
  52. Decode HTML-entities like `&amp;`, `&nbsp;`, etc. Default: `true`. **Warning:** disabling this option may cause output which is not conform HTML5 specification.
  53. ##### options.locationInfo
  54. Enables source code location information for the nodes. Default: `false`. When enabled, each node (except root node) has `__location` property, which contains `start` and `end` indices of the node in the source code. If element was implicitly created by the parser it's `__location` property will be `null`. In case the node is not an empty element, `__location` has two addition properties `startTag` and `endTag` which contain location information for individual tags in a fashion similar to `__location` property.
  55. *Example:*
  56. ```js
  57. var parse5 = require('parse5');
  58. //Instantiate new parser with default tree adapter
  59. var parser1 = new parse5.Parser();
  60. //Instantiate new parser with htmlparser2 tree adapter
  61. var parser2 = new parse5.Parser(parse5.TreeAdapters.htmlparser2);
  62. ```
  63. #### &bull; Parser.parse(html)
  64. Parses specified `html` string. Returns `document` node.
  65. *Example:*
  66. ```js
  67. var document = parser.parse('<!DOCTYPE html><html><head></head><body>Hi there!</body></html>');
  68. ```
  69. #### &bull; Parser.parseFragment(htmlFragment, [contextElement])
  70. Parses given `htmlFragment`. Returns `documentFragment` node. Optional `contextElement` argument specifies context in which given `htmlFragment` will be parsed (consider it as setting `contextElement.innerHTML` property). If `contextElement` argument is not specified then `<template>` element will be used as a context and fragment will be parsed in 'forgiving' manner.
  71. *Example:*
  72. ```js
  73. var documentFragment = parser.parseFragment('<table></table>');
  74. //Parse html fragment in context of the parsed <table> element
  75. var trFragment = parser.parseFragment('<tr><td>Shake it, baby</td></tr>', documentFragment.childNodes[0]);
  76. ```
  77. ---------------------------------------
  78. ### Class: SimpleApiParser
  79. Provides [SAX](https://en.wikipedia.org/wiki/Simple_API_for_XML)-style HTML parsing functionality.
  80. #### &bull; SimpleApiParser.ctor(handlers, [options])
  81. Creates new reusable instance of the `SimpleApiParser`. `handlers` argument specifies object that contains parser's event handlers. Possible events and their signatures are shown in the example.
  82. `options` object provides the parsing algorithm modifications:
  83. ##### options.decodeHtmlEntities
  84. Decode HTML-entities like `&amp;`, `&nbsp;`, etc. Default: `true`. **Warning:** disabling this option may cause output which is not conform HTML5 specification.
  85. ##### options.locationInfo
  86. Enables source code location information for the tokens. Default: `false`. When enabled, each node handler receives `location` object as it's last argument. `location` object contains `start` and `end` indices of the token in the source code.
  87. *Example:*
  88. ```js
  89. var parse5 = require('parse5');
  90. var parser = new parse5.SimpleApiParser({
  91. doctype: function(name, publicId, systemId /*, [location] */) {
  92. //Handle doctype here
  93. },
  94. startTag: function(tagName, attrs, selfClosing /*, [location] */) {
  95. //Handle start tags here
  96. },
  97. endTag: function(tagName /*, [location] */) {
  98. //Handle end tags here
  99. },
  100. text: function(text /*, [location] */) {
  101. //Handle texts here
  102. },
  103. comment: function(text /*, [location] */) {
  104. //Handle comments here
  105. }
  106. });
  107. ```
  108. #### &bull; SimpleApiParser.parse(html)
  109. Raises parser events for the given `html`.
  110. *Example:*
  111. ```js
  112. var parse5 = require('parse5');
  113. var parser = new parse5.SimpleApiParser({
  114. text: function(text) {
  115. console.log(text);
  116. }
  117. });
  118. parser.parse('<body>Yo!</body>');
  119. ```
  120. ---------------------------------------
  121. ### Class: Serializer
  122. Provides tree-to-HTML serialization functionality.
  123. **Note:** prior to v1.2.0 this class was called `TreeSerializer`. However, it's still accessible as `parse5.TreeSerializer` for backward compatibility.
  124. #### &bull; Serializer.ctor([treeAdapter, options])
  125. Creates new reusable instance of the `Serializer`. Optional `treeAdapter` argument specifies input tree format. If `treeAdapter` argument is not specified, `default` tree adapter will be used.
  126. `options` object provides the serialization algorithm modifications:
  127. ##### options.encodeHtmlEntities
  128. HTML-encode characters like `<`, `>`, `&`, etc. Default: `true`. **Warning:** disabling this option may cause output which is not conform HTML5 specification.
  129. *Example:*
  130. ```js
  131. var parse5 = require('parse5');
  132. //Instantiate new serializer with default tree adapter
  133. var serializer1 = new parse5.Serializer();
  134. //Instantiate new serializer with htmlparser2 tree adapter
  135. var serializer2 = new parse5.Serializer(parse5.TreeAdapters.htmlparser2);
  136. ```
  137. #### &bull; Serializer.serialize(node)
  138. Serializes the given `node`. Returns HTML string.
  139. *Example:*
  140. ```js
  141. var document = parser.parse('<!DOCTYPE html><html><head></head><body>Hi there!</body></html>');
  142. //Serialize document
  143. var html = serializer.serialize(document);
  144. //Serialize <body> element content
  145. var bodyInnerHtml = serializer.serialize(document.childNodes[0].childNodes[1]);
  146. ```
  147. ---------------------------------------
  148. ## Testing
  149. Test data is adopted from [html5lib project](https://github.com/html5lib). Parser is covered by more than 8000 test cases.
  150. To run tests:
  151. ```
  152. $ npm test
  153. ```
  154. ## Custom tree adapter
  155. You can create a custom tree adapter so parse5 can work with your own DOM-tree implementation.
  156. Just pass your adapter implementation to the parser's constructor as an argument:
  157. ```js
  158. var Parser = require('parse5').Parser;
  159. var myTreeAdapter = {
  160. //Adapter methods...
  161. };
  162. //Instantiate parser
  163. var parser = new Parser(myTreeAdapter);
  164. ```
  165. Sample implementation can be found [here](https://github.com/inikulin/parse5/blob/master/lib/tree_adapters/default.js).
  166. The custom tree adapter should implement all methods exposed via `exports` in the sample implementation.
  167. ## Questions or suggestions?
  168. If you have any questions, please feel free to create an issue [here on github](https://github.com/inikulin/parse5/issues).
  169. ## Author
  170. [Ivan Nikulin](https://github.com/inikulin) (ifaaan@gmail.com)