Web scraping: trích xuất dữ liệu từ web, chuyển phi cấu trúc thành có cấu trúc. 6 thư viện phổ biến.
So sánh nhanh
| Thư viện | Loại | JS Support | Độ phức tạp | Dùng cho |
|---|---|---|---|---|
| urllib | Built-in HTTP | Không | Thấp | Request đơn giản |
| requests | HTTP client | Không | Thấp | API, REST, HTML tĩnh |
| BeautifulSoup | Parser HTML | Không | Trung bình | Parse, extract DOM |
| lxml | Parser XML/HTML | Không | Trung bình | Tốc độ cao, XPath |
| Selenium | Browser automation | Có | Cao | SPA, dynamic JS, test |
| MechanicalSoup | Stateful browser | Không | Trung bình | Form, login, redirect |
1. urllib (stdlib)
from urllib.request import urlopen
html = urlopen("https://www.tutorialspoint.com/").read()
print(html[:500])
2. Requests (khuyên dùng cho HTTP)
import requests
r = requests.get('https://www.tutorialspoint.com/')
print(r.status_code) # 200
print(r.encoding) # UTF-8
print(r.headers['Content-Type'])
print(r.url)
print(r.elapsed)
3. BeautifulSoup (parse HTML)
from bs4 import BeautifulSoup
import requests
r = requests.get("https://www.tutorialspoint.com/")
soup = BeautifulSoup(r.text, 'html.parser')
for link in soup.find_all('a'):
print(link.get('href'))
4. lxml (parser nhanh, XPath)
from lxml import etree root = etree.Element('html') etree.SubElement(root, 'head') etree.SubElement(root, 'title') etree.SubElement(root, 'body') print(etree.tostring(root, pretty_print=True).decode()) #
5. Selenium (JavaScript rendering)
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
service = Service('/path/to/chromedriver')
driver = webdriver.Chrome(service=service)
driver.get('https://www.tutorialspoint.com/')
print(driver.title)
driver.quit()
6. MechanicalSoup (form, session)
import mechanicalsoup
browser = mechanicalsoup.StatefulBrowser()
browser.open("https://www.tutorialspoint.com/")
browser.follow_link("forms")
print(browser.get_url())
Khuyên dùng
- HTML tĩnh + API: requests + BeautifulSoup/lxml.
- Cần JS, SPA, click, scroll: Selenium/Playwright.
- Login, form, session: MechanicalSoup/requests.Session.
- Tuân thủ
robots.txt, rate limit, terms of service.