You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

4 anni fa
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. <h1 align="center">cheerio</h1>
  2. <h5 align="center">Fast, flexible & lean implementation of core jQuery designed specifically for the server.</h5>
  3. <div align="center">
  4. <a href="https://github.com/cheeriojs/cheerio/actions?query=workflow%3ACI+branch%3Amain">
  5. <img src="https://img.shields.io/github/workflow/status/cheeriojs/cheerio/CI/main" alt="Build Status">
  6. </a>
  7. <a href="https://coveralls.io/github/cheeriojs/cheerio">
  8. <img src="https://img.shields.io/coveralls/github/cheeriojs/cheerio/main" alt="Coverage">
  9. </a>
  10. <a href="#backers">
  11. <img src="https://img.shields.io/opencollective/backers/cheerio" alt="OpenCollective backers">
  12. </a>
  13. <a href="#sponsors">
  14. <img src="https://img.shields.io/opencollective/sponsors/cheerio" alt="OpenCollective sponsors">
  15. </a>
  16. </div>
  17. <br>
  18. [中文文档 (Chinese Readme)](https://github.com/cheeriojs/cheerio/wiki/Chinese-README)
  19. ```js
  20. const cheerio = require('cheerio');
  21. const $ = cheerio.load('<h2 class="title">Hello world</h2>');
  22. $('h2.title').text('Hello there!');
  23. $('h2').addClass('welcome');
  24. $.html();
  25. //=> <html><head></head><body><h2 class="title welcome">Hello there!</h2></body></html>
  26. ```
  27. ## Note
  28. We are currently working on the 1.0.0 release of cheerio on the `main` branch. The source code for the last published version, `0.22.0`, can be found [here](https://github.com/cheeriojs/cheerio/tree/aa90399c9c02f12432bfff97b8f1c7d8ece7c307).
  29. ## Installation
  30. `npm install cheerio`
  31. ## Features
  32. **&#10084; Familiar syntax:**
  33. Cheerio implements a subset of core jQuery. Cheerio removes all the DOM inconsistencies and browser cruft from the jQuery library, revealing its truly gorgeous API.
  34. **&#991; Blazingly fast:**
  35. Cheerio works with a very simple, consistent DOM model. As a result parsing, manipulating, and rendering are incredibly efficient.
  36. **&#10049; Incredibly flexible:**
  37. Cheerio wraps around [parse5](https://github.com/inikulin/parse5) parser and can optionally use @FB55's forgiving [htmlparser2](https://github.com/fb55/htmlparser2/). Cheerio can parse nearly any HTML or XML document.
  38. ## Cheerio is not a web browser
  39. Cheerio parses markup and provides an API for traversing/manipulating the resulting data structure. It does not interpret the result as a web browser does. Specifically, it does _not_ produce a visual rendering, apply CSS, load external resources, or execute JavaScript. This makes Cheerio **much, much faster than other solutions**. If your use case requires any of this functionality, you should consider projects like [Puppeteer](https://github.com/puppeteer/puppeteer) or [JSDom](https://github.com/jsdom/jsdom).
  40. ## API
  41. ### Markup example we'll be using:
  42. ```html
  43. <ul id="fruits">
  44. <li class="apple">Apple</li>
  45. <li class="orange">Orange</li>
  46. <li class="pear">Pear</li>
  47. </ul>
  48. ```
  49. This is the HTML markup we will be using in all of the API examples.
  50. ### Loading
  51. First you need to load in the HTML. This step in jQuery is implicit, since jQuery operates on the one, baked-in DOM. With Cheerio, we need to pass in the HTML document.
  52. This is the _preferred_ method:
  53. ```js
  54. // ES6 or TypeScript:
  55. import * as cheerio from 'cheerio';
  56. // In other environments:
  57. const cheerio = require('cheerio');
  58. const $ = cheerio.load('<ul id="fruits">...</ul>');
  59. $.html();
  60. //=> <html><head></head><body><ul id="fruits">...</ul></body></html>
  61. ```
  62. Similar to web browser contexts, `load` will introduce `<html>`, `<head>`, and `<body>` elements if they are not already present. You can set `load`'s third argument to `false` to disable this.
  63. ```js
  64. const $ = cheerio.load('<ul id="fruits">...</ul>', null, false);
  65. $.html();
  66. //=> '<ul id="fruits">...</ul>'
  67. ```
  68. Optionally, you can also load in the HTML by passing the string as the context:
  69. ```js
  70. $('ul', '<ul id="fruits">...</ul>');
  71. ```
  72. Or as the root:
  73. ```js
  74. $('li', 'ul', '<ul id="fruits">...</ul>');
  75. ```
  76. If you need to modify parsing options for XML input, you may pass an extra
  77. object to `.load()`:
  78. ```js
  79. const $ = cheerio.load('<ul id="fruits">...</ul>', {
  80. xml: {
  81. normalizeWhitespace: true,
  82. },
  83. });
  84. ```
  85. The options in the `xml` object are taken directly from [htmlparser2](https://github.com/fb55/htmlparser2/wiki/Parser-options), therefore any options that can be used in `htmlparser2` are valid in cheerio as well. When `xml` is set, the default options are:
  86. ```js
  87. {
  88. xmlMode: true,
  89. decodeEntities: true, // Decode HTML entities.
  90. withStartIndices: false, // Add a `startIndex` property to nodes.
  91. withEndIndices: false, // Add an `endIndex` property to nodes.
  92. }
  93. ```
  94. For a full list of options and their effects, see [domhandler](https://github.com/fb55/DomHandler) and
  95. [htmlparser2's options](https://github.com/fb55/htmlparser2/wiki/Parser-options).
  96. Some users may wish to parse markup with the `htmlparser2` library, and
  97. traverse/manipulate the resulting structure with Cheerio. This may be the case
  98. for those upgrading from pre-1.0 releases of Cheerio (which relied on
  99. `htmlparser2`), for those dealing with invalid markup (because `htmlparser2` is
  100. more forgiving), or for those operating in performance-critical situations
  101. (because `htmlparser2` may be faster in some cases). Note that "more forgiving"
  102. means `htmlparser2` has error-correcting mechanisms that aren't always a match
  103. for the standards observed by web browsers. This behavior may be useful when
  104. parsing non-HTML content.
  105. To support these cases, `load` also accepts a `htmlparser2`-compatible data
  106. structure as its first argument. Users may install `htmlparser2`, use it to
  107. parse input, and pass the result to `load`:
  108. ```js
  109. // Usage as of htmlparser2 version 6:
  110. const htmlparser2 = require('htmlparser2');
  111. const dom = htmlparser2.parseDocument(document, options);
  112. const $ = cheerio.load(dom);
  113. ```
  114. ### Selectors
  115. Cheerio's selector implementation is nearly identical to jQuery's, so the API is very similar.
  116. #### \$( selector, [context], [root] )
  117. `selector` searches within the `context` scope which searches within the `root` scope. `selector` and `context` can be a string expression, DOM Element, array of DOM elements, or cheerio object. `root` is typically the HTML document string.
  118. This selector method is the starting point for traversing and manipulating the document. Like jQuery, it's the primary method for selecting elements in the document.
  119. ```js
  120. $('.apple', '#fruits').text();
  121. //=> Apple
  122. $('ul .pear').attr('class');
  123. //=> pear
  124. $('li[class=orange]').html();
  125. //=> Orange
  126. ```
  127. ##### XML Namespaces
  128. You can select with XML Namespaces but [due to the CSS specification](https://www.w3.org/TR/2011/REC-css3-selectors-20110929/#attribute-selectors), the colon (`:`) needs to be escaped for the selector to be valid.
  129. ```js
  130. $('[xml\\:id="main"');
  131. ```
  132. ### Rendering
  133. When you're ready to render the document, you can call the `html` method on the "root" selection:
  134. ```js
  135. $.root().html();
  136. //=> <html>
  137. // <head></head>
  138. // <body>
  139. // <ul id="fruits">
  140. // <li class="apple">Apple</li>
  141. // <li class="orange">Orange</li>
  142. // <li class="pear">Pear</li>
  143. // </ul>
  144. // </body>
  145. // </html>
  146. ```
  147. If you want to render the [`outerHTML`](https://developer.mozilla.org/en-US/docs/Web/API/Element/outerHTML) of a selection, you can use the `html` utility functon:
  148. ```js
  149. cheerio.html($('.pear'));
  150. //=> <li class="pear">Pear</li>
  151. ```
  152. By default, `html` will leave some tags open. Sometimes you may instead want to render a valid XML document. For example, you might parse the following XML snippet:
  153. ```js
  154. const $ = cheerio.load(
  155. '<media:thumbnail url="http://www.foo.com/keyframe.jpg" width="75" height="50" time="12:05:01.123"/>'
  156. );
  157. ```
  158. ... and later want to render to XML. To do this, you can use the 'xml' utility function:
  159. ```js
  160. $.xml();
  161. //=> <media:thumbnail url="http://www.foo.com/keyframe.jpg" width="75" height="50" time="12:05:01.123"/>
  162. ```
  163. You may also render the text content of a Cheerio object using the `text` static method:
  164. ```js
  165. const $ = cheerio.load('This is <em>content</em>.');
  166. cheerio.text($('body'));
  167. //=> This is content.
  168. ```
  169. ### Plugins
  170. Once you have loaded a document, you may extend the prototype or the equivalent `fn` property with custom plugin methods:
  171. ```js
  172. const $ = cheerio.load('<html><body>Hello, <b>world</b>!</body></html>');
  173. $.prototype.logHtml = function () {
  174. console.log(this.html());
  175. };
  176. $('body').logHtml(); // logs "Hello, <b>world</b>!" to the console
  177. ```
  178. If you're using TypeScript, you should also add a type definition for your new method:
  179. ```ts
  180. declare module 'cheerio' {
  181. interface Cheerio<T> {
  182. logHtml(this: Cheerio<T>): void;
  183. }
  184. }
  185. ```
  186. ### The "DOM Node" object
  187. Cheerio collections are made up of objects that bear some resemblance to [browser-based DOM nodes](https://developer.mozilla.org/en-US/docs/Web/API/Node). You can expect them to define the following properties:
  188. - `tagName`
  189. - `parentNode`
  190. - `previousSibling`
  191. - `nextSibling`
  192. - `nodeValue`
  193. - `firstChild`
  194. - `childNodes`
  195. - `lastChild`
  196. ## Screencasts
  197. [https://vimeo.com/31950192](https://vimeo.com/31950192)
  198. > This video tutorial is a follow-up to Nettut's "How to Scrape Web Pages with Node.js and jQuery", using cheerio instead of JSDOM + jQuery. This video shows how easy it is to use cheerio and how much faster cheerio is than JSDOM + jQuery.
  199. ## Cheerio in the real world
  200. Are you using cheerio in production? Add it to the [wiki](https://github.com/cheeriojs/cheerio/wiki/Cheerio-in-Production)!
  201. ## Sponsors
  202. Does your company use Cheerio in production? Please consider [sponsoring this project](https://github.com/cheeriojs/cheerio?sponsor=1)! Your help will allow maintainers to dedicate more time and resources to its development and support.
  203. <!-- BEGIN SPONSORS: sponsor -->
  204. <a href="https://substack.com/" target="_blank">![Substack](https://avatars.githubusercontent.com/u/53023767?v=4&s=128)</a>
  205. <a href="https://www.airbnb.com/" target="_blank">![Airbnb](https://images.opencollective.com/airbnb/d327d66/logo.png)</a>
  206. <!-- END SPONSORS -->
  207. ## Backers
  208. [Become a backer](https://github.com/cheeriojs/cheerio?sponsor=1) to show your support for Cheerio and help us maintain and improve this open source project.
  209. <!-- BEGIN SPONSORS: backer -->
  210. <a href="https://medium.com/norch" target="_blank">![Espen Klem](https://images.opencollective.com/espenklem/6075b19/avatar.png)</a>
  211. <a href="https://nishant-singh.com" target="_blank">![Nishant Singh](https://avatars.githubusercontent.com/u/10304344?u=9cd1389a1a8211b64979ca3693f96d90f5bf0be9&v=4&s=128)</a>
  212. <!-- END SPONSORS -->
  213. ## Special Thanks
  214. This library stands on the shoulders of some incredible developers. A special thanks to:
  215. **&#8226; @FB55 for node-htmlparser2 & CSSSelect:**
  216. Felix has a knack for writing speedy parsing engines. He completely re-wrote both @tautologistic's `node-htmlparser` and @harry's `node-soupselect` from the ground up, making both of them much faster and more flexible. Cheerio would not be possible without his foundational work
  217. **&#8226; @jQuery team for jQuery:**
  218. The core API is the best of its class and despite dealing with all the browser inconsistencies the code base is extremely clean and easy to follow. Much of cheerio's implementation and documentation is from jQuery. Thanks guys.
  219. **&#8226; @visionmedia:**
  220. The style, the structure, the open-source"-ness" of this library comes from studying TJ's style and using many of his libraries. This dude consistently pumps out high-quality libraries and has always been more than willing to help or answer questions. You rock TJ.
  221. ## License
  222. MIT