Tự động thu thập giá sản phẩm từ website về Excel và Database
Nội dung
1. Giới thiệu
Trong thời đại chuyển đổi số, việc tự động hóa quy trình thu thập và lưu trữ dữ liệu từ các trang thương mại điện tử là giải pháp thiết thực cho cá nhân và doanh nghiệp. Nó giúp dễ dàng theo dõi biến động giá, so sánh sản phẩm và hỗ trợ ra quyết định mua sắm hoặc kinh doanh hiệu quả.
Bài viết này hướng dẫn cách sử dụng Python để tự động lấy dữ liệu giá của hai dòng sản phẩm phổ biến – iPhone và iPad – từ website Thế Giới Di Động:
- iPhone: https://www.thegioididong.com/dtdd-apple-iphone
- iPad: https://www.thegioididong.com/may-tinh-bang-apple-ipad
Dữ liệu thu thập bao gồm:
- Tên sản phẩm
- Giá bán
- Loại sản phẩm (iPhone hoặc iPad)
- Đường dẫn sản phẩm
- Ngày lấy dữ liệu
2. Chuẩn bị môi trường Python và thư viện
Cài đặt Python
- Truy cập: https://www.python.org/downloads/
- Tải về và cài đặt phiên bản mới nhất
- Đảm bảo tích chọn tùy chọn “Add Python to PATH” trong quá trình cài đặt

Cài đặt thư viện Python
Mở Command Prompt hoặc Terminal, chạy lệnh:
pip install requests beautifulsoup4 pandas openpyxl pyodbc
requests
: Gửi yêu cầu HTTPbeautifulsoup4
: Phân tích HTMLpandas
: Xử lý và xuất dữ liệuopenpyxl
: Ghi file Excel (.xlsx)pyodbc
: Kết nối với SQL Server
3. Thu thập dữ liệu và xuất ra Excel
Tạo file Python
- Mở Notepad (hoặc bất kỳ trình soạn thảo văn bản nào như Notepad++, VS Code, Sublime Text…).
- Sao chép toàn bộ đoạn mã Python bên dưới và dán vào cửa sổ Notepad.
import requests
from bs4 import BeautifulSoup
import pandas as pd
from datetime import datetime
def fetch_products(url, loai):
headers = {"User-Agent": "Mozilla/5.0"}
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, "html.parser")
products = soup.select("ul.listproduct li")
today = datetime.today().date()
data = []
for p in products:
name_tag = p.select_one("h3")
price_tag = p.select_one("strong.price")
link_tag = p.select_one("a")
if name_tag and price_tag and link_tag:
ten = name_tag.text.strip()
try:
gia = int(price_tag.text.replace(".", "").replace("₫", "").strip())
except ValueError:
gia = None
link = "https://www.thegioididong.com" + link_tag["href"]
data.append({
"ten": ten,
"gia": gia,
"loai": loai,
"link": link,
"ngay_lay": today
})
return data
urls_and_types = [
("https://www.thegioididong.com/dtdd-apple-iphone", "iPhone"),
("https://www.thegioididong.com/may-tinh-bang-apple-ipad", "iPad"),
]
all_data = []
for url, loai in urls_and_types:
all_data.extend(fetch_products(url, loai))
df = pd.DataFrame(all_data)
# Sắp xếp: iPhone trước, iPad sau
df = df.sort_values(by=["loai", "ten"], key=lambda col: col.map({"iPhone": 0, "iPad": 1}))
# Xuất ra Excel
today_str = datetime.today().strftime('%d-%m-%Y')
filename = f"SanPhamTGDD_{today_str}.xlsx"
df.to_excel(filename, index=False)
print(f"Đã xuất dữ liệu ra file Excel: {filename}")
- Chọn File > Save As…, sau đó:
- Đặt tên file, ví dụ:
SanPham_TGDD_Excel.py
- Chọn Save as type là All Files
- Chọn vị trí lưu (ví dụ: thư mục
D:\Demo
) - Nhấn Save để lưu lại
- Đặt tên file, ví dụ:

Chạy file Python
- Nhấp đúp vào
SanPham_TGDD_Excel.py
để chạy - Hoặc mở Command Prompt, điều hướng đến thư mục chứa file chạy lệnh:
python SanPham_TGDD_Excel.py
Kiểm tra kết quả
Sau khi chạy, bạn sẽ thấy file Excel có tên dạng SanPhamTGDD_dd-MM-yyyy.xlsx
chứa danh sách sản phẩm iPhone và iPad.

4. Lưu dữ liệu vào SQL Server
Tạo cơ sở dữ liệu và bảng
Chạy đoạn SQL sau trong SQL Server Management Studio:
-- Tạo CSDL
CREATE DATABASE SanPhamTGDD
GO
-- Tạo bảng
USE SanPhamTGDD
GO
CREATE TABLE SanPham (
id INT IDENTITY PRIMARY KEY,
ten NVARCHAR(255),
gia INT,
loai NVARCHAR(50),
link NVARCHAR(500),
ngay_lay DATE
)
GO
Mã Python đẩy dữ liệu vào Database
import requests
from bs4 import BeautifulSoup
import pyodbc
from datetime import datetime
SERVER = r'LAPTOP\SQL1'
DATABASE = 'SanPhamTGDD'
USERNAME = 'sa'
PASSWORD = '123456'
conn_str = (
f"DRIVER={{ODBC Driver 17 for SQL Server}};"
f"SERVER={SERVER};"
f"DATABASE={DATABASE};"
f"UID={USERNAME};"
f"PWD={PASSWORD}"
)
conn = pyodbc.connect(conn_str)
cursor = conn.cursor()
def fetch_and_insert(url, loai):
headers = {"User-Agent": "Mozilla/5.0"}
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, "html.parser")
products = soup.select("ul.listproduct li")
today = datetime.today().date()
count = 0
for p in products:
name_tag = p.select_one("h3")
price_tag = p.select_one("strong.price")
link_tag = p.select_one("a")
if name_tag and price_tag and link_tag:
ten = name_tag.text.strip()
try:
gia = int(price_tag.text.replace(".", "").replace("₫", "").strip())
except ValueError:
gia = None
link = "https://www.thegioididong.com" + link_tag["href"]
cursor.execute("""
INSERT INTO sanpham (ten, gia, loai, link, ngay_lay)
VALUES (?, ?, ?, ?, ?)
""", (ten, gia, loai, link, today))
count += 1
conn.commit()
print(f"Đã lưu {count} sản phẩm loại {loai} vào bảng sanpham.")
urls_and_types = [
("https://www.thegioididong.com/dtdd-apple-iphone", "iPhone"),
("https://www.thegioididong.com/may-tinh-bang-apple-ipad", "iPad"),
]
for url, loai in urls_and_types:
fetch_and_insert(url, loai)
conn.close()
Lưu đoạn mã Python trên với tên SanPham_TGDD_Database.py
và chạy chương trình tương tự như đã hướng dẫn ở bước trước.
Minh họa bên dưới là kết quả sau khi chạy thành công:

5. Tổng kết
Qua bài viết này, bạn đã học được cách sử dụng Python để tự động thu thập dữ liệu giá sản phẩm từ website thương mại điện tử, sau đó xuất ra file Excel và lưu vào cơ sở dữ liệu SQL Server. Đây là một giải pháp hiệu quả giúp tiết kiệm thời gian, giảm thao tác thủ công và hỗ trợ phân tích dữ liệu trong hoạt động cá nhân hoặc kinh doanh.
Đặc biệt, bạn hoàn toàn có thể kết hợp với Task Scheduler của Windows để thiết lập lịch chạy tự động hàng ngày hoặc theo giờ cố định, giúp hệ thống thu thập dữ liệu hoàn toàn tự động, không cần can thiệp thủ công.
Bạn có thể mở rộng mã nguồn để:
- Thu thập thêm các loại sản phẩm khác.
- Áp dụng cho nhiều website khác nhau.
- Thêm tính năng kiểm tra thay đổi giá theo thời gian.
Chúc bạn thành công!