Web Scraping Với JavaScript Và Node.js: Hướng Dẫn Đầy Đủ
JavaScript không chỉ cho frontend. Với Node.js, bạn có thể scrape web hiệu quả như bất kỳ ngôn ngữ backend nào.
Tại Sao Node.js Cho Scraping?
- Không bị CORS: Browser bị chặn, Node.js thì không
- Async native: Event loop xử lý nhiều requests hiệu quả
- Ecosystem mạnh: Cheerio, Puppeteer, Playwright
- Scale dễ: Không cần refresh browser 500 lần
Setup Project
1. Khởi tạo project
mkdir node-scraping
cd node-scraping
npm init -y
2. Cấu hình ES modules
Trong package.json, thêm:
"type": "module"
3. Cài Cheerio
npm install cheerio
Script Scraping Cơ Bản
import * as cheerio from 'cheerio';
const URL = 'https://quotes.toscrape.com/';
async function scrape() {
// Fetch HTML
const res = await fetch(URL);
const html = await res.text();
// Parse với Cheerio
const $ = cheerio.load(html);
const quotes = [];
// Extract data
$('.quote').each((i, el) => {
const text = $(el).find('.text').text().trim();
const author = $(el).find('.author').text().trim();
const tags = [];
$(el).find('.tags .tag').each((j, tagEl) => {
tags.push($(tagEl).text().trim());
});
quotes.push({ text, author, tags });
});
console.log(JSON.stringify(quotes, null, 2));
}
await scrape();
Cheerio vs Puppeteer
| Tool | Use Case | Speed |
|---|---|---|
| Cheerio | Static HTML | Rất nhanh |
| Puppeteer | JavaScript rendering | Chậm hơn |
| Playwright | Cross-browser + JS | Chậm hơn |
Scrape Hacker News
import * as cheerio from 'cheerio';
const URL = 'https://news.ycombinator.com';
async function run() {
const res = await fetch(URL);
const html = await res.text();
const $ = cheerio.load(html);
const titles = [];
$('.athing .titleline > a').each((i, el) => {
titles.push($(el).text());
});
console.log(titles);
}
run();
Node.js Với Proxy
import { HttpsProxyAgent } from 'https-proxy-agent';
const agent = new HttpsProxyAgent(
'http://user:pass@proxy.vinaproxy.com:8080'
);
const res = await fetch(url, { agent });
Event Loop Là Gì?
Node.js là single-threaded nhưng xử lý async rất hiệu quả. Không block = không chậm.
VinaProxy + Node.js
- Residential proxy cho scraping ổn định
- Tích hợp dễ với fetch/axios
- Giá chỉ $0.5/GB
