BeautifulSoup giúp dễ dàng trích xuất thẻ <title> từ tài liệu HTML - thông tin quan trọng cho SEO, bookmark, hiển thị tab trình duyệt.
Cài đặt
pip install beautifulsoup4
Ví dụ lấy title
from bs4 import BeautifulSoup
import requests
url = "https://en.wikipedia.org/wiki/Algorithm"
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")
print("Tiêu đề trang:")
print(soup.title)
print("Nội dung title:", soup.title.string if soup.title else "Không có title")
Kết quả
Tiêu đề trang:Algorithm − Wikipedia Nội dung title: Algorithm − Wikipedia
Giải thích
soup.titletrả về đối tượng Tag<title>....soup.title.stringtrả về text bên trong (nếu chỉ có text node duy nhất).soup.title.texthoặcsoup.title.get_text()an toàn hơn, gom tất cả text con.- Nếu trang không có thẻ title,
soup.titletrả vềNone.
Mở rộng: Lấy các thẻ heading khác
# Lấy tất cả h1, h2, h3
for heading in soup.find_all(['h1', 'h2', 'h3']):
print(f"{heading.name}: {heading.get_text(strip=True)}")
Lưu ý
- Web scraping cần tuân thủ
robots.txtvà ToS của trang web. - Wikipedia cho phép scrape có giới hạn rate, khuyến khích dùng API chính thức.
- Xử lý lỗi network, timeout, encoding.