X-ray

The next web scraper. See through the noise.

README

x-ray

Last version Build Status Coverage Status Dependency status Dev Dependencies Status NPM Status
Node version OpenCollective OpenCollective Gitter

  1. ```js
  2. var Xray = require('x-ray')
  3. var x = Xray()

  4. x('https://blog.ycombinator.com/', '.post', [
  5.   {
  6.     title: 'h1 a',
  7.     link: '.article-title@href'
  8.   }
  9. ])
  10.   .paginate('.nav-previous a@href')
  11.   .limit(3)
  12.   .write('results.json')
  13. ```

Installation


  1. ```
  2. npm install x-ray
  3. ```

Features


- Flexible schema: Supports strings, arrays, arrays of objects, and nested object structures. The schema is not tied to the structure of the page you're scraping, allowing you to pull the data in the structure of your choosing.

- Composable: The API is entirely composable, giving you great flexibility in how you scrape each page.

- Pagination support: Paginate through websites, scraping each page. X-ray also supports a request delay and a pagination limit. Scraped pages can be streamed to a file, so if there's an error on one page, you won't lose what you've already scraped.

- Crawler support: Start on one page and move to the next easily. The flow is predictable, following
  a breadth-first crawl through each of the pages.

- Responsible: X-ray has support for concurrency, throttles, delays, timeouts and limits to help you scrape any page responsibly.

- Pluggable drivers: Swap in different scrapers depending on your needs. Currently supports HTTP and PhantomJS driver drivers. In the future, I'd like to see a Tor driver for requesting pages through the Tor network.

Selector API


xray(url, selector)(fn)


Scrape the url for the following selector, returning an object in the callback fn.
The selector takes an enhanced jQuery-like string that is also able to select on attributes. The syntax for selecting on attributes is selector@attribute. If you do not supply an attribute, the default is selecting the innerText.

Here are a few examples:

- Scrape a single tag

  1. ```js
  2. xray('http://google.com', 'title')(function(err, title) {
  3.   console.log(title) // Google
  4. })
  5. ```

- Scrape a single class

  1. ```js
  2. xray('http://reddit.com', '.content')(fn)
  3. ```

- Scrape an attribute

  1. ```js
  2. xray('http://techcrunch.com', 'img.logo@src')(fn)
  3. ```

- Scrape innerHTML

  1. ```js
  2. xray('http://news.ycombinator.com', 'body@html')(fn)
  3. ```

xray(url, scope, selector)


You can also supply a scope to each selector. In jQuery, this would look something like this: $(scope).find(selector).

xray(html, scope, selector)


Instead of a url, you can also supply raw HTML and all the same semantics apply.

  1. ```js
  2. var html = '<body><h2>Pear</h2></body>'
  3. x(html, 'body', 'h2')(function(err, header) {
  4.   header // => Pear
  5. })
  6. ```

API


xray.driver(driver)


Specify a driver to make requests through. Available drivers include:

- request - A simple driver built around request. Use this to set headers, cookies or http methods.
- phantom - A high-level browser automation library. Use this to render pages or when elements need to be interacted with, or when elements are created dynamically using javascript (e.g.: Ajax-calls).

xray.stream()


Returns Readable Stream of the data. This makes it easy to build APIs around x-ray. Here's an example with Express:

  1. ```js
  2. var app = require('express')()
  3. var x = require('x-ray')()

  4. app.get('/', function(req, res) {
  5.   var stream = x('http://google.com', 'title').stream()
  6.   stream.pipe(res)
  7. })
  8. ```

xray.write([path])


Stream the results to a path.

If no path is provided, then the behavior is the same as .stream().

xray.then(cb)


Constructs a Promise object and invoke its then function with a callback cb. Be sure to invoke then() at the last step of xray method chaining, since the other methods are not promisified.

  1. ```js
  2. x('https://dribbble.com', 'li.group', [
  3.   {
  4.     title: '.dribbble-img strong',
  5.     image: '.dribbble-img [data-src]@data-src'
  6.   }
  7. ])
  8.   .paginate('.next_page@href')
  9.   .limit(3)
  10.   .then(function(res) {
  11.     console.log(res[0]) // prints first result
  12.   })
  13.   .catch(function(err) {
  14.     console.log(err) // handle error in promise
  15.   })
  16. ```

xray.paginate(selector)


Select a url from a selector and visit that page.

xray.limit(n)


Limit the amount of pagination to n requests.

xray.abort(validator)


Abort pagination if validator function returns true.
The validator function receives two arguments:

- result: The scrape result object for the current page.
- nextUrl: The URL of the next page to scrape.

xray.delay(from, [to])


Delay the next request between from and to milliseconds.
If only from is specified, delay exactly from milliseconds.
  1. ```js
  2. var x = Xray().delay('1s', '10s')
  3. ```

xray.concurrency(n)


Set the request concurrency to n. Defaults to Infinity.
  1. ```js
  2. var x = Xray().concurrency(2)
  3. ```

xray.throttle(n, ms)


Throttle the requests to n requests per ms milliseconds.
  1. ```js
  2. var x = Xray().throttle(2, '1s')
  3. ```

xray.timeout (ms)


Specify a timeout of ms milliseconds for each request.
  1. ```js
  2. var x = Xray().timeout(30)
  3. ```

Collections


X-ray also has support for selecting collections of tags. While x('ul', 'li') will only select the first list item in an unordered list, x('ul', ['li']) will select all of them.

Additionally, X-ray supports "collections of collections" allowing you to smartly select all list items in all lists with a command like this: x(['ul'], ['li']).

Composition


X-ray becomes more powerful when you start composing instances together. Here are a few possibilities:

Crawling to another site


  1. ```js
  2. var Xray = require('x-ray')
  3. var x = Xray()

  4. x('http://google.com', {
  5.   main: 'title',
  6.   image: x('#gbar a@href', 'title') // follow link to google images
  7. })(function(err, obj) {
  8.   /*
  9.   {
  10.     main: 'Google',
  11.     image: 'Google Images'
  12.   }
  13. */
  14. })
  15. ```

Scoping a selection


  1. ```js
  2. var Xray = require('x-ray')
  3. var x = Xray()

  4. x('http://mat.io', {
  5.   title: 'title',
  6.   items: x('.item', [
  7.     {
  8.       title: '.item-content h2',
  9.       description: '.item-content section'
  10.     }
  11.   ])
  12. })(function(err, obj) {
  13.   /*
  14.   {
  15.     title: 'mat.io',
  16.     items: [
  17.       {
  18.         title: 'The 100 Best Children\'s Books of All Time',
  19.         description: 'Relive your childhood with TIME\'s list...'
  20.       }
  21.     ]
  22.   }
  23. */
  24. })
  25. ```

Filters


Filters can specified when creating a new Xray instance. To apply filters to a value, append them to the selector using |.

  1. ```js
  2. var Xray = require('x-ray')
  3. var x = Xray({
  4.   filters: {
  5.     trim: function(value) {
  6.       return typeof value === 'string' ? value.trim() : value
  7.     },
  8.     reverse: function(value) {
  9.       return typeof value === 'string'
  10.         ? value
  11.             .split('')
  12.             .reverse()
  13.             .join('')
  14.         : value
  15.     },
  16.     slice: function(value, start, end) {
  17.       return typeof value === 'string' ? value.slice(start, end) : value
  18.     }
  19.   }
  20. })

  21. x('http://mat.io', {
  22.   title: 'title | trim | reverse | slice:2,3'
  23. })(function(err, obj) {
  24.   /*
  25.   {
  26.     title: 'oi'
  27.   }
  28. */
  29. })
  30. ```

Examples


- selector: simple string selector
- collections: selects an object
- arrays: selects an array
- collections of collections: selects an array of objects
- array of arrays: selects an array of arrays

In the Wild


- Levered Returns: Uses x-ray to pull together financial data from various unstructured sources around the web.

Resources


- Video: https://egghead.io/lessons/node-js-intro-to-web-scraping-with-node-and-x-ray

Backers


Support us with a monthly donation and help us continue our activities. [Become a backer]


Sponsors


Become a sponsor and get your logo on our website and on our README on Github with a link to your site. [Become a sponsor]


License


MIT