XPath Cho Web Scraping: Hướng Dẫn Từ Cơ Bản Đến Nâng Cao
XPath là ngôn ngữ chọn elements trong XML/HTML. Mạnh hơn CSS selectors cho complex selections.
XPath vs CSS Selectors
| Feature | XPath | CSS |
|---|---|---|
| Text matching | ✅ Có | ❌ Không |
| Parent selection | ✅ Có | ❌ Không |
| Sibling navigation | ✅ Mạnh | ⚠️ Hạn chế |
| Readability | Phức tạp hơn | Đơn giản hơn |
Cú Pháp Cơ Bản
# Chọn tất cả div
//div
# Chọn div có class
//div[@class='product']
# Chọn theo id
//div[@id='main']
# Chọn con trực tiếp
//ul/li
# Chọn con bất kỳ level
//div//a
Text Matching (Siêu Mạnh!)
# Chứa text
//button[contains(text(), 'Add to Cart')]
# Text chính xác
//span[text()='Price']
# Starts-with
//a[starts-with(@href, '/product')]
# Contains trong attribute
//div[contains(@class, 'item')]
Position Selection
# Phần tử đầu tiên
//li[1]
# Phần tử cuối
//li[last()]
# 3 phần tử đầu
//li[position() <= 3]
# Phần tử chẵn
//li[position() mod 2 = 0]
Navigation
# Parent
//span[@class='price']/parent::div
# Siblings
//h2/following-sibling::p
//h2/preceding-sibling::div
# Ancestor
//span/ancestor::article
Python + lxml
from lxml import html
import requests
response = requests.get('https://example.com')
tree = html.fromstring(response.content)
# Single element
title = tree.xpath('//h1/text()')[0]
# Multiple elements
prices = tree.xpath('//span[@class="price"]/text()')
# Attribute
links = tree.xpath('//a/@href')
# Complex
products = tree.xpath('//div[contains(@class, "product")]')
for p in products:
name = p.xpath('.//h2/text()')[0]
price = p.xpath('.//span[@class="price"]/text()')[0]
print(f"{name}: {price}")
Selenium + XPath
from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
driver.get('https://example.com')
# Find element
element = driver.find_element(By.XPATH, '//button[text()="Submit"]')
# Find multiple
items = driver.find_elements(By.XPATH, '//div[@class="item"]')
Tips
- Dùng XPath khi cần text matching
- Dùng XPath khi cần navigate to parent
- Test XPath trong browser DevTools
- Tránh XPath quá dài (fragile)
VinaProxy + XPath Scraping
- Scrape complex sites với XPath
- Proxy rotation cho scale
- Giá chỉ $0.5/GB
