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
+49 -9
View File
@@ -83,20 +83,60 @@ class ShopeeBot:
time.sleep(4) # Chờ Shopee convert link và hiện kết quả time.sleep(4) # Chờ Shopee convert link và hiện kết quả
# 8. Lấy tỷ lệ hoa hồng # 8. Lấy tỷ lệ hoa hồng, link mới và giá
print("Đang đọc tỷ lệ hoa hồng...") print("Đang đọc kết quả trên màn hình...")
commission_element = self.d(textContains="Tỷ lệ hoa hồng")
if commission_element.exists: import json
text_result = commission_element.get_text() import re
# Text có dạng "Tỷ lệ hoa hồng 10,5%"
return text_result 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: 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 # Nếu không tìm thấy, dump UI ra để debug
xml_dump = self.d.dump_hierarchy() xml_dump = self.d.dump_hierarchy()
with open("error_dump.xml", "w", encoding="utf-8") as f: with open("error_dump.xml", "w", encoding="utf-8") as f:
f.write(xml_dump) 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: 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)}"}
+6 -4
View File
@@ -26,13 +26,15 @@ async def get_commission_endpoint(req: CommissionRequest):
bot = ShopeeBot(device_ip=target_ip) bot = ShopeeBot(device_ip=target_ip)
result = bot.get_commission(req.link) result = bot.get_commission_rate(req.link)
# Nếu đã có status thì gộp thẳng các thuộc tính của result vào JSON trả về
if isinstance(result, dict) and "status" in result:
return result
return { return {
"status": "success", "status": "success",
"link": req.link, "commission": result
"commission": result,
"connected_ip": target_ip if target_ip else "auto-detect"
} }
except Exception as e: except Exception as e:
logging.error(f"Lỗi API: {str(e)}") logging.error(f"Lỗi API: {str(e)}")
+3 -1
View File
@@ -13,6 +13,8 @@ if __name__ == "__main__":
# Đoạn này sẽ chạy đúng quy trình: Mở Shopee -> Tôi -> Tiếp Thị Liên Kết -> Chuyển Đổi # Đoạn này sẽ chạy đúng quy trình: Mở Shopee -> Tôi -> Tiếp Thị Liên Kết -> Chuyển Đổi
result = bot.get_commission_rate(test_url) result = bot.get_commission_rate(test_url)
import json
print("\n===============================") print("\n===============================")
print(f"🎯 KẾT QUẢ: {result}") print("🎯 KẾT QUẢ TỪ BOT:")
print(json.dumps(result, indent=2, ensure_ascii=False))
print("===============================\n") print("===============================\n")