import uiautomator2 as u2 import time import logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) class ShopeeBot: def __init__(self, device_ip: str = ""): """ Khởi tạo kết nối qua Wireless Debugging :param device_ip: IP và Port của điện thoại. Nếu để trống, u2 sẽ tự kết nối thiết bị mặc định """ self.device_ip = device_ip try: if self.device_ip: logger.info(f"Đang kết nối tới thiết bị {self.device_ip}...") self.d = u2.connect(self.device_ip) else: logger.info("Đang tự động dò tìm thiết bị ADB đang kết nối...") self.d = u2.connect() logger.info(f"Kết nối thành công: {self.d.info}") except Exception as e: logger.error(f"Lỗi kết nối ADB: {e}") raise def get_commission(self, product_link: str) -> str: """ Mở Shopee, dán link và lấy phần trăm hoa hồng """ # 1. Khởi động app Shopee logger.info("Mở ứng dụng Shopee...") self.d.app_start("com.shopee.vn") time.sleep(3) # Đợi app load, có thể tuỳ chỉnh # 2. Bấm vào thanh tìm kiếm (Ví dụ thao tác cơ bản) logger.info("Tìm thanh tìm kiếm...") # Ở đây tôi dùng textContains, bạn cần dùng công cụ Weditor để điều chỉnh lại theo đúng giao diện search_box = self.d(textContains="Tìm kiếm", className="android.widget.TextView") if search_box.exists: search_box.click() time.sleep(1) else: logger.warning("Không tìm thấy thanh tìm kiếm ở trang hiện tại.") # 3. Dán link và enter logger.info("Đang dán link sản phẩm...") # Ở màn hình nhập liệu, giả sử có một ô đang focus try: self.d(focused=True).set_text(product_link) self.d.press("enter") # Đợi Shopee load trang sản phẩm (mạng chậm cần chờ lâu hơn) time.sleep(6) except Exception as e: logger.error(f"Lỗi dán link: {e}") # 4. Tìm và đọc text phần trăm hoa hồng logger.info("Đang quét màn hình lấy hoa hồng...") # LƯU Ý: Phần text/ID này phụ thuộc vào giao diện tài khoản Affiliate Shopee của bạn. try: # Ví dụ giả định Element chứa chữ hoa hồng: commission_element = self.d(textContains="Hoa hồng") if commission_element.exists: # Lấy tất cả text của element đó (ví dụ "Hoa hồng: 15%") commission_text = commission_element.get_text() logger.info(f"Lấy thành công: {commission_text}") return commission_text else: logger.error("Không tìm thấy thông tin hoa hồng trên màn hình.") return "Không tìm thấy thông tin" except Exception as e: logger.error(f"Lỗi khi đọc dữ liệu màn hình: {e}") return "Lỗi quét dữ liệu"