Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Web Scraping Python với BeautifulSoup

BeautifulSoup (package bs4) là thư viện parse HTML/XML phổ biến, dễ dùng cho web scraping.

Cài đặt

pip install beautifulsoup4 requests lxml
  • requests: HTTP client thân thiện.
  • lxml: Parser nhanh (khuyên dùng).

Ví dụ 1: Trích xuất link từ HTML string

from bs4 import BeautifulSoup

html_doc = '''
TutorialsPoint
NSE India
Google
GitHub
'''

soup = BeautifulSoup(html_doc, 'lxml')  # hoặc 'html.parser'

for tag in soup.find_all('a'):
    print(tag.get('href'))
    # print(tag.text)  # Text bên trong thẻ
https://tutorialspoint.com
https://nseindia.com
https://google.com
https://github.com

Ví dụ 2: Crawl link chứa "python" từ python.org

from bs4 import BeautifulSoup
import requests
import re

url = "https://www.python.org"
response = requests.get(url, timeout=10)
soup = BeautifulSoup(response.content, 'lxml')

for a in soup.find_all('a', href=True):
    href = a['href']
    if re.search(r'python', href, re.I):
        print(f"Python URL: {href}")

Các phương thức tìm kiếm phổ biến

Phương thứcMô tả
find(name, attrs, ...)Tìm 1 thẻ đầu tiên khớp
find_all(name, attrs, ...)Tìm TẤT CẢ thẻ khớp (trả list)
select(css_selector)CSS selector (ví dụ: 'div.content > p')
select_one(css_selector)1 thẻ đầu tiên khớp CSS selector

Ví dụ CSS Selector

# Tất cả  trong 
links = soup.select('div.content a') # Thẻ có id="main" main = soup.select_one('#main') # Thẻ có class="highlight" items = soup.select('.highlight') # Attribute selector images = soup.select('img[src$=".png"]') # src kết thúc .png

Xử lý encoding & lỗi thường gặp

response = requests.get(url)
response.encoding = response.apparent_encoding  # Tự detect encoding
soup = BeautifulSoup(response.text, 'lxml')

# Hoặc dùng response.content (bytes) -> BeautifulSoup tự detect
soup = BeautifulSoup(response.content, 'lxml')

Best Practices & Legal

  • Kiểm tra robots.txt và Terms of Service trước khi scrape.
  • Rate limiting: time.sleep(1) giữa các request.
  • Dùng User-Agent header hợp lý.
  • Xử lý exception: requests.exceptions.RequestException.
  • Cân nhắc API chính thức nếu có (tốt hơn scraping).

Alternatives

  • Scrapy: Framework scraping mạnh, async, built-in pipeline.
  • Selenium/Playwright: Render JavaScript (dynamic sites).
  • httpx: Async HTTP client hiện đại.