Hướng Dẫn Selenium Web Scraping Với Python (2026)

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

Hướng Dẫn Selenium Web Scraping Với Python (2026)

Selenium là công cụ browser automation mạnh mẽ nhất cho web scraping. Đặc biệt hiệu quả với các trang JavaScript-heavy.

Tại Sao Dùng Selenium?

  • Render JavaScript: Scraper tĩnh không thấy data load bằng JS
  • Tương tác như người dùng: Click, scroll, fill forms
  • Chụp screenshot: Debug và monitoring
  • Handle dynamic content: Infinite scroll, lazy loading

Cài Đặt Selenium 2026

Option 1: pip (classic)

# Tạo virtual environment
python -m venv .venv
source .venv/bin/activate  # Linux/Mac

# Cài Selenium
pip install --upgrade selenium

Option 2: uv (modern)

uv init selenium-scraper
cd selenium-scraper
uv add selenium

Tin vui 2026: Selenium Manager tự động download driver phù hợp. Không cần tải ChromeDriver thủ công nữa!

Script Selenium Cơ Bản

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By

def main():
    # Cấu hình headless
    opts = Options()
    opts.add_argument("--headless")
    
    # Khởi tạo driver
    driver = webdriver.Chrome(options=opts)
    driver.get("https://example.com")
    
    # Lấy title
    print(driver.title)
    
    # Chụp screenshot
    driver.save_screenshot("page.png")
    
    # Tìm links
    links = driver.find_elements(By.TAG_NAME, "a")
    for link in links[:5]:
        text = link.text.strip()
        href = link.get_attribute("href")
        print(f"{text}: {href}")
    
    driver.quit()

if __name__ == "__main__":
    main()

Headless Mode

Chạy browser không hiển thị window – perfect cho server và automation:

opts = Options()
opts.add_argument("--headless")
opts.add_argument("--no-sandbox")  # Cần cho Docker/CI
opts.add_argument("--disable-dev-shm-usage")

Selenium Với Proxy

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

opts = Options()
opts.add_argument("--headless")
opts.add_argument("--proxy-server=http://user:pass@proxy.vinaproxy.com:8080")

driver = webdriver.Chrome(options=opts)
driver.get("https://example.com")
print(driver.title)
driver.quit()

Xử Lý Lỗi Phổ Biến

  • Browser not found: Cài Chrome hoặc Firefox
  • Timeout: Clear cache hoặc upgrade Selenium
  • Crash trong Docker: Thêm –no-sandbox

VinaProxy + Selenium

  • Residential proxy tránh bị detect
  • Auto-rotation cho scraping lớn
  • Giá chỉ $0.5/GB

Xem Hướng Dẫn Tích Hợp Selenium →