feat: implement FastAPI service to expose Shopee commission scraping automation via REST API

This commit is contained in:
Victor Phan
2026-07-21 10:02:51 +07:00
parent 6156bc7bb3
commit adbfb43a48
3 changed files with 59 additions and 15 deletions
+50 -10
View File
@@ -83,20 +83,60 @@ class ShopeeBot:
time.sleep(4) # Chờ Shopee convert link và hiện kết quả
# 8. Lấy tỷ lệ hoa hồng
print("Đang đọc tỷ lệ hoa hồng...")
commission_element = self.d(textContains="Tỷ lệ hoa hồng")
# 8. Lấy tỷ lệ hoa hồng, link mới và giá
print("Đang đọc kết quả trên màn hình...")
if commission_element.exists:
text_result = commission_element.get_text()
# Text có dạng "Tỷ lệ hoa hồng 10,5%"
return text_result
else:
import json
import re
result_data = {
"status": "success",
"commission": "",
"affiliate_link": "",
"price": "",
"message": "Trích xuất thành công"
}
# Quét toàn bộ text trên màn hình để tìm các thông tin
# Lấy tất cả các thành phần có text
all_texts = []
for elem in self.d(textMatches="(?s).*"):
t = elem.get_text()
if t and t not in all_texts:
all_texts.append(t)
for t in all_texts:
# 1. Tìm Tỷ lệ hoa hồng
if "Tỷ lệ hoa hồng" in t:
# Rút gọn lấy mỗi số (VD: "Tỷ lệ hoa hồng 10,5%" -> "10,5%")
match = re.search(r'Tỷ lệ hoa hồng\s*([\d,.]+%?)', t)
if match:
result_data["commission"] = match.group(1)
else:
result_data["commission"] = t.replace("Tỷ lệ hoa hồng", "").strip()
# 2. Tìm Affiliate Link (thường có s.shopee.vn)
if "s.shopee.vn" in t or "shp.ee" in t:
# Trích xuất phần URL, bỏ số thứ tự ví dụ "1. https://s.shopee.vn/..."
match = re.search(r'(https?://[^\s]+)', t)
if match:
result_data["affiliate_link"] = match.group(1)
# 3. Tìm Giá bán
# Thường có chữ "đ" ở đầu: đ192.000 hoặc đ90.000
if t.startswith("đ") or t.startswith(""):
result_data["price"] = t
if not result_data["commission"]:
# Nếu không tìm thấy, dump UI ra để debug
xml_dump = self.d.dump_hierarchy()
with open("error_dump.xml", "w", encoding="utf-8") as f:
f.write(xml_dump)
return "Lỗi: Không thấy Tỷ lệ hoa hồng (Đã lưu error_dump.xml)"
result_data["status"] = "error"
result_data["message"] = "Không thấy Tỷ lệ hoa hồng (Đã lưu error_dump.xml)"
# Trả về dạng Dictionary (FastAPI sẽ tự chuyển thành JSON cho n8n)
return result_data
except Exception as e:
return f"Lỗi không xác định: {str(e)}"
return {"status": "error", "message": f"Lỗi không xác định: {str(e)}"}