Cấp độ: intermediate35 phútminMiễn phíFreeYoung CreatorYoung Creator

Python: Xây web scraper đơn giảnPython: Build a simple web scraper

Script lấy dữ liệu từ web và lưu CSVA script that fetches web data and saves as CSV

Bạn sẽ học gìWhat you will learn

  • Dùng requests.get()Use requests.get()
  • Parse HTML với BeautifulSoupParse HTML with BeautifulSoup
  • Trích xuất và lưu dữ liệuExtract and save data

Bạn sẽ tạo gìWhat you will build

Script lấy dữ liệu từ web và lưu CSVA script that fetches web data and saves as CSV

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.

python
                      
                        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.

python
                      
                        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.

python
                      
                        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")
                      
                    

Bài tập thực hànhHands-on exercises

1Scrape 5 quyển sách đầu tiên từ books.toscrape.com: lấy tên và giá, in ra màn hình.Scrape the first 5 books from books.toscrape.com: get name and price, print to screen.

Gợi ýHint

requests.get → BeautifulSoup → find_all("article", class_="product_pod") → lặp 5 cái đầu.requests.get → BeautifulSoup → find_all("article", class_="product_pod") → loop first 5.

Lời giảiSolution
python
                      
                        import requests
from bs4 import BeautifulSoup

url = "https://books.toscrape.com"
response = requests.get(url, headers={"User-Agent": "Mozilla/5.0"})
soup = BeautifulSoup(response.text, "html.parser")
books = soup.find_all("article", class_="product_pod")

for book in books[:5]:
    ten = book.find("h3").find("a")["title"]
    gia = book.find("p", class_="price_color").text
    print(f"{ten} — {gia}")
                      
                    

2Lưu 20 quyển sách đầu tiên vào file CSV với cột: Tên, Giá, Tình trạng.Save the first 20 books to a CSV file with columns: Title, Price, Availability.

Gợi ýHint

Dùng module csv. Mở file với encoding="utf-8". writerow cho header và mỗi sách.Use the csv module. Open file with encoding="utf-8". writerow for header and each book.

Lời giảiSolution
python
                      
                        import requests
from bs4 import BeautifulSoup
import csv

url = "https://books.toscrape.com"
response = requests.get(url, headers={"User-Agent": "Mozilla/5.0"})
soup = BeautifulSoup(response.text, "html.parser")
books = soup.find_all("article", class_="product_pod")

with open("sach.csv", "w", newline="", encoding="utf-8") as f:
    writer = csv.writer(f)
    writer.writerow(["Tên", "Giá", "Tình trạng"])
    for book in books[:20]:
        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 20 sách vào sach.csv")
                      
                    

Kiểm traQuiz

Chọn đáp án đúng cho mỗi câu. Nhấn để xem giải thích.Choose the correct answer for each question. Click to see explanation.

Câu 1: Web scraping là gì?Q1: What is web scraping?

Câu 2: Lệnh nào tải trang web trong Python?Q2: Which command fetches a web page in Python?

Câu 3: BeautifulSoup dùng để làm gì?Q3: What is BeautifulSoup used for?

Câu 4: response.status_code = 200 nghĩa là gì?Q4: What does response.status_code = 200 mean?

Code mẫuSample code

python
                import requests
from bs4 import BeautifulSoup
import csv

# Lấy trang / Fetch page
url = "https://books.toscrape.com"
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')

# Lấy tên sách / Get book titles
books = soup.find_all('h3')
for book in books[:5]:
    print(book.find('a')['title'])