Nội dung bài họcLesson content
Web scraping là gì?What is web scraping?
Web scraping là tự động lấy dữ liệu từ trang web. Thay vì copy thủ công, bạn viết code tải trang, phân tích HTML, trích xuất thông tin. Ứng dụng: theo dõi giá, thu thập tin tức, phân tích đối thủ. Cài đặt: pip install requests beautifulsoup4.Web scraping is automatically extracting data from web pages. Instead of manual copy, you write code to download the page, parse HTML, and extract info. Uses: price tracking, news gathering, competitor analysis. Install: pip install requests beautifulsoup4.
Dùng requests để tải trang webUsing requests to fetch web pages
requests.get(url) tải trang web. response.text chứa HTML. response.status_code: 200 = thành công, 404 = không tìm thấy. Luôn kiểm tra status_code trước khi parse. Thêm User-Agent header để không bị chặn.requests.get(url) fetches a web page. response.text contains HTML. response.status_code: 200 = success, 404 = not found. Always check status_code before parsing. Add a User-Agent header to avoid being blocked.
import requests
url = "https://books.toscrape.com"
headers = {"User-Agent": "Mozilla/5.0"}
response = requests.get(url, headers=headers)
print(response.status_code) # 200
print(len(response.text)) # Độ dài HTML
# print(response.text[:500]) # Xem 500 ký tự đầu
Parse HTML với BeautifulSoupParsing HTML with BeautifulSoup
BeautifulSoup biến HTML thô thành cây đối tượng dễ tìm. soup = BeautifulSoup(html, "html.parser"). Dùng soup.find("tag") tìm thẻ đầu, soup.find_all("tag") tìm tất cả. Truy cập thuộc tính: element["href"], element.text.BeautifulSoup turns raw HTML into an easy-to-search object tree. soup = BeautifulSoup(html, "html.parser"). Use soup.find("tag") for the first tag, soup.find_all("tag") for all. Access attributes: element["href"], element.text.
from bs4 import BeautifulSoup
soup = BeautifulSoup(response.text, "html.parser")
# Tìm tất cả thẻ h2
titles = soup.find_all("h2")
for t in titles[:3]:
print(t.text.strip())
# Tìm theo class
books = soup.find_all("article", class_="product_pod")
print(f"Số sách: {len(books)}")
# Lấy giá của sách đầu tiên
price = books[0].find("p", class_="price_color").text
print(f"Giá: {price}")
Lưu dữ liệu vào CSVSaving data to CSV
Module csv có sẵn trong Python. Mở file với open(), tạo csv.writer, dùng writer.writerow() để ghi từng dòng. CSV mở được bằng Excel. Đây là cách lưu dữ liệu scrape được để phân tích sau.The csv module is built into Python. Open a file with open(), create a csv.writer, use writer.writerow() to write each row. CSV opens in Excel. This is how you save scraped data for later analysis.
import csv
with open("sach.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerow(["Tên", "Giá", "Tình trạng"]) # Header
for book in books[:10]:
ten = book.find("h3").find("a")["title"]
gia = book.find("p", class_="price_color").text
trang_thai = book.find("p", class_="instock").text.strip()
writer.writerow([ten, gia, trang_thai])
print("Đã lưu 10 sách vào sach.csv")