background preloader

Node.js

Facebook Twitter

Website crawling with node.js / jakub.fedyczak.net. Introduction When you need to quickly scrape some data from a website, here's a simple solution using: node.jsrequest - HTTP clientcheerio - HTML parser with jQuery-like API I'll ignore error checking for simplicity.

Website crawling with node.js / jakub.fedyczak.net

Don't ever do that - especially with node.js - it'll kick your ass. As always - everything using CoffeeScript. Crawling a site We need some initialization: request = require 'request' cheerio = require 'cheerio' async = require 'async' Initialize cookie jar in case we're handling cookie-aware site using HTTP redirects: jar = request.jar() Now start actual crawling: request followRedirect: true uri: ' timeout: 10000 jar: jar , (err, res, body) -> $ = cheerio.load body $('a').each -> console.log "#{$(@).text()} -> #{$(@).attr 'href'}" We use cheerio to parse request body and find anchor text of each link on site. Use Node.js to Extract Data from the Web for Fun and Profit. Need to automate pulling some data from a web page?

Use Node.js to Extract Data from the Web for Fun and Profit

Or want to mash up some unstructured data from a blog post with another data source. No API for getting at the data… ! @#$@#$… No Problem… Web scraping to the rescue. What is web scraping? … you may be asking… Web scraping consists of programmatically (typically with no browser involved) retrieving the contents of web pages and extracting data from them. In this article, I’m going to show you a pretty powerful set of tools for scraping web content quickly and easily using Javascript and Node.js. I recently needed to be able to crawl a (modestly) large number of pages and sift through them looking for patterns.

I have a guilty pleasure. If you don’t already have Node.js installed or haven’t updated it in a while. Npm install cheerio Once Cheerio has been installed, we can get down to business. The Node Toolbox - Node.js happiness. Mikeal/request. Bnoguchi/everyauth. LESS « The Dynamic Stylesheet language. Mongoose Schemas v3.8.1. If you haven't yet done so, please take a minute to read the quickstart to get an idea of how Mongoose works.

Mongoose Schemas v3.8.1

If you are migrating from 2.x to 3.x please take a moment to read the migration guide. Defining your schema Everything in Mongoose starts with a Schema. Each schema maps to a MongoDB collection and defines the shape of the documents within that collection. If you want to add additional keys later, use the Schema#add method. Each key in our blogSchema defines a property in our documents which will be cast to its associated SchemaType. The permitted SchemaTypes are StringNumberDateBufferBooleanMixedObjectIdArrayRead more about them here. Schemas not only define the structure of your document and casting of properties, they also define document instance methods, static Model methods, compound indexes and document lifecycle hooks called middleware.

Creating a model To use our schema definition, we need to convert our blogSchema into a Model we can work with. Instance methods Statics Indexes. Фреймворк Express - руководство пользователя. Var app = express.createServer(); app.get('/', function(req, res) { res.send('Hello World'); }); app.listen(3000); Возможности Понятная маршрутизация Помощники перенаправления (redirect helpers) Динамические помощники представлений Опции представлений уровня приложения Взаимодействие с контентом Монтирование приложений Ориентированность на высокую производительность Рендеринг шаблонов и поддержка фрагментных шаблонов (view partials) Конфигурации, быстро переключаемые под разные задачи (development, production, и т.д.)

Фреймворк Express - руководство пользователя

Хранимые в сессии всплывающие сообщения (flash messages) Сделано на основе Connect Скрипт express для быстрой генерации каркаса приложения Высокое покрытие тестами Установка $ npm install express или, чтобы иметь доступ к команде express, установите глобально: $ npm install -g express Быстрый старт Проще всего начать работу с Express можно выполнив команду express, которая сгенерирует приложение: Создание приложения: $ npm install -g express $ express /tmp/foo && cd /tmp/foo. Полный набор пакетов для разработки с помощью NodeJS. Типичный стек технологий для использования с Node.js. Пишем веб-паука на Node.js. Sub-Adult Male Jumping spider Сегодняшнее упражнение будет несложным, но интересным :) Мы напишем веб-паука на Node.js.

Пишем веб-паука на Node.js

Он будет скачивать страницы, вынимать оттуда все найденные ссылки и повторять процесс для каждой из них. Спайдер сам по себе штука довольно простая. В нашем случае он будет состоять всего из двух компонент. Нам надо подключаться и скачивать файлы, и надо как то извлекать из них ссылки. Парсер Итак, для web-спайдера нам потребуется парсер HTML. Для сборки требуется scons — система сборки проекта, написанная на Python: Либо можно скачать его отсюда и установить командой make. Теперь нужны заголовки для libxml2 (если их ещё нет).