Cấp độ: intermediate 35 phútmin Miễn phí Free Young Creator Young Creator

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

Script lấy dữ liệu từ web và lưu CSV A 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 BeautifulSoup Parse HTML with BeautifulSoup
  • Trích xuất và lưu dữ liệu Extract and save data

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

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

Code mẫu Sample 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'])