BeautifulSoup là thư viện Python phổ biến để phân tích cú pháp HTML/XML, hỗ trợ trích xuất dữ liệu từ trang web (web scraping).
Cài đặt
pip install beautifulsoup4
Ví dụ trích xuất tất cả link
from bs4 import BeautifulSoup
import requests
url = "https://en.wikipedia.org/wiki/Algorithm"
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")
print("Các liên kết href:")
for link in soup.find_all('a'):
href = link.get('href')
if href:
print(href)
Kết quả mẫu
Các liên kết href: https://stats.wikimedia.org/#/en.wikipedia.org https://foundation.wikimedia.org/wiki/Cookie_statement https://wikimediafoundation.org/ https://www.mediawiki.org/ ... (nhiều link khác)
Giải thích
requests.get()tải nội dung HTML của trang.BeautifulSoup(html, "html.parser")tạo đối tượng parse tree.soup.find_all('a')tìm tất cả thẻ<a>(anchor/link).link.get('href')lấy giá trị thuộc tính href (an toàn hơnlink['href']vì trả None nếu không có).- Có thể lọc thêm: link nội bộ/ngoại bộ, bỏ qua fragment (#...), javascript:, mailto:, v.v.
Lưu ý pháp lý và đạo đức
- Kiểm tra
robots.txtcủa trang web trước khi scrape. - Tuân thủ Terms of Service.
- Thêm delay giữa các request để không quá tải server.
- Sử dụng User-Agent hợp lệ.