Bắt Đầu Web Scraping: Hướng Dẫn Cho Người Mới

Trở lại Tin tức
Tin tức

Bắt Đầu Web Scraping: Hướng Dẫn Cho Người Mới

Chưa biết gì về scraping? Bài viết hướng dẫn từng bước cho người mới bắt đầu.

Web Scraping Là Gì?

Web scraping = tự động thu thập data từ websites. Thay vì copy-paste thủ công, code sẽ làm việc đó cho bạn.

Bạn Cần Gì?

  • Python (miễn phí)
  • Text editor (VS Code recommended)
  • Terminal/Command Prompt
  • Proxy (cho scale lớn)

Bước 1: Cài Python

# Kiểm tra Python đã cài chưa
python --version

# Nếu chưa, download từ python.org
# Chọn "Add to PATH" khi cài

Bước 2: Cài Libraries

# Mở terminal, chạy:
pip install requests beautifulsoup4 lxml

# Kiểm tra
pip list

Bước 3: Scraper Đầu Tiên

# scraper.py
import requests
from bs4 import BeautifulSoup

# 1. Fetch webpage
url = 'https://quotes.toscrape.com'
response = requests.get(url)

# 2. Parse HTML
soup = BeautifulSoup(response.text, 'lxml')

# 3. Find data
quotes = soup.select('.quote')

# 4. Extract và print
for quote in quotes:
    text = quote.select_one('.text').text
    author = quote.select_one('.author').text
    print(f"{text}\n- {author}\n")

Bước 4: Chạy Script

# Trong terminal:
python scraper.py

# Output:
# "The world as we have created it..."
# - Albert Einstein
# ...

Bước 5: Lưu Data

import csv

# Collect data
data = []
for quote in quotes:
    data.append({
        'text': quote.select_one('.text').text,
        'author': quote.select_one('.author').text
    })

# Save to CSV
with open('quotes.csv', 'w', newline='', encoding='utf-8') as f:
    writer = csv.DictWriter(f, fieldnames=['text', 'author'])
    writer.writeheader()
    writer.writerows(data)

print(f"Saved {len(data)} quotes to quotes.csv")

Bước 6: Thêm Proxy

# Khi cần scrape nhiều hoặc protected sites
proxy = 'http://user:pass@proxy.vinaproxy.com:8080'

response = requests.get(
    url,
    proxies={'http': proxy, 'https': proxy}
)

Hiểu CSS Selectors

# Chọn theo class
soup.select('.product-name')

# Chọn theo ID
soup.select('#main-content')

# Chọn theo tag
soup.select('h1')

# Chọn theo attribute
soup.select('[data-id="123"]')

# Nested selection
soup.select('.product .price')

Tips Cho Beginners

  1. Start simple: Scrape sites dễ trước
  2. Learn DevTools: Right-click → Inspect
  3. Add delays: time.sleep(1) giữa requests
  4. Handle errors: try/except
  5. Test small: 10 pages trước khi scrape 1000

Practice Sites

Common Errors

# Error: No module named 'bs4'
# Fix: pip install beautifulsoup4

# Error: Connection timeout
# Fix: Thêm timeout, check internet

# Error: 403 Forbidden
# Fix: Thêm User-Agent header

Next Steps

  1. Học pagination (nhiều pages)
  2. Học async scraping (nhanh hơn)
  3. Học Playwright (JavaScript sites)
  4. Dùng proxy (scale lên)

VinaProxy Cho Beginners

  • Easy setup – just add proxy URL
  • Affordable – $0.5/GB
  • Perfect để học và scale

Bắt Đầu Ngay →