This commit is contained in:
HuangHai
2026-01-16 19:50:39 +08:00
parent 95a96e2f0e
commit 8a9d71f1de
12 changed files with 1 additions and 367 deletions

View File

@@ -410,7 +410,7 @@ class TeLaiDianCrawler(BaseCrawler):
entered_price_path = take_screenshot(d, f"tld_detail_price_after_enter_{int(time.time())}.jpg")
logger.info(f"[电价页] 入口点击后的电价页截图已保存: {entered_price_path}")
await asyncio.sleep(1.0)
await asyncio.sleep(0.5)
# 1. 向上滚动到顶部(不断下拉直到看到最上面的 00:00
logger.info("正在向上滚动价格列表到顶部 (快速多次滚动以尽快看到 00:00)...")

View File

@@ -1,44 +0,0 @@
# coding=utf-8
import sys
import os
import hashlib
import cv2
import numpy as np
# Add project root to sys.path
project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../../"))
sys.path.append(project_root)
from Apps.YeLiTe.Kit import get_image_content_md5
from Apps.YeLiTe.Config import Setting
def check_result():
output_dir = os.path.join(project_root, "Output")
files = sorted([f for f in os.listdir(output_dir) if f.startswith("verify_step1_list_")])
if not files:
print("No verification files found.")
return
latest_timestamp = files[-1].split("_")[-1].replace(".jpg", "")
print(f"Checking latest run: {latest_timestamp}")
step1 = os.path.join(output_dir, f"verify_step1_list_{latest_timestamp}.jpg")
step4 = os.path.join(output_dir, f"verify_step4_after_{latest_timestamp}.jpg")
if not os.path.exists(step4):
print("Step 4 file not found. Script might have failed mid-way.")
return
md5_1 = get_image_content_md5(step1, top_ratio=Setting.SAFE_EXCLUDE_RATIO, bottom_ratio=Setting.BOTTOM_SAFE_EXCLUDE_RATIO)
md5_4 = get_image_content_md5(step4, top_ratio=Setting.SAFE_EXCLUDE_RATIO, bottom_ratio=Setting.BOTTOM_SAFE_EXCLUDE_RATIO)
print(f"Step 1 MD5: {md5_1}")
print(f"Step 4 MD5: {md5_4}")
if md5_1 != md5_4:
print(">>> RESULT: SUCCESS (MD5 Changed)")
else:
print(">>> RESULT: FAILURE (MD5 Identical)")
if __name__ == "__main__":
check_result()

Binary file not shown.

Before

Width:  |  Height:  |  Size: 259 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 269 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 197 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 210 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 210 KiB

View File

@@ -1,82 +0,0 @@
# coding=utf-8
import sys
import os
import cv2
import numpy as np
import time
# Add project root to sys.path
project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../../"))
sys.path.append(project_root)
try:
from Apps.YeLiTe.Kit import detect_cards_cv
from Apps.YeLiTe.Config import Setting
except ImportError as e:
print(f"Import Error: {e}")
print(f"Current sys.path: {sys.path}")
sys.exit(1)
def test_detection_and_click_simulation(image_path):
print(f"Loading image: {image_path}")
if not os.path.exists(image_path):
print(f"Error: File not found: {image_path}")
return
# 1. Run detection
print("Running detect_cards_cv...")
cards = detect_cards_cv(image_path, top_ratio=Setting.SAFE_EXCLUDE_RATIO, bottom_ratio=Setting.BOTTOM_SAFE_EXCLUDE_RATIO)
if not cards:
print("No cards detected!")
return
print(f"Detected {len(cards)} cards.")
# 2. Draw results
img = cv2.imread(image_path)
for i, box in enumerate(cards):
x1, y1, x2, y2 = box
# Draw green box
cv2.rectangle(img, (x1, y1), (x2, y2), (0, 255, 0), 2)
# Calculate click point (center)
center_x = int((x1 + x2) / 2)
center_y = int((y1 + y2) / 2)
# Draw click point (Red Circle)
cv2.circle(img, (center_x, center_y), 10, (0, 0, 255), -1)
# Add label
label = f"#{i+1} ({center_x}, {center_y})"
cv2.putText(img, label, (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 255), 2)
print(f"Card #{i+1}: Box=[{x1}, {y1}, {x2}, {y2}], Click Point=({center_x}, {center_y})")
# 3. Save result
output_filename = f"result_{os.path.basename(image_path)}"
output_path = os.path.join(os.path.dirname(__file__), output_filename)
cv2.imwrite(output_path, img)
print(f"Result saved to: {output_path}")
if __name__ == "__main__":
# Default to the latest list_*.jpg in Output if no argument provided
target_image = ""
if len(sys.argv) > 1:
target_image = sys.argv[1]
else:
output_dir = os.path.join(project_root, "Output")
if os.path.exists(output_dir):
files = [f for f in os.listdir(output_dir) if f.startswith("list_") and f.endswith(".jpg")]
if files:
# Sort by time (filename usually contains timestamp)
files.sort(reverse=True)
target_image = os.path.join(output_dir, files[0])
if target_image:
test_detection_and_click_simulation(target_image)
else:
print("No target image found. Please provide an image path as an argument.")

View File

@@ -1,129 +0,0 @@
# coding=utf-8
import sys
import os
import time
import asyncio
import uiautomator2 as u2
import cv2
# Add project root to sys.path
project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../../"))
sys.path.append(project_root)
try:
from Apps.YeLiTe.Kit import detect_cards_cv, draw_rectangles, take_screenshot, get_image_content_md5
from Apps.YeLiTe.Config import Setting
except ImportError as e:
print(f"Import Error: {e}")
sys.exit(1)
async def run_verification():
print(">>> [Step 0] 连接设备...")
try:
d = u2.connect()
info = d.info
print(f"设备已连接: {info.get('productName', 'Unknown Device')}")
except Exception as e:
print(f"设备连接失败: {e}")
return
# 这里我们假设已经在列表页,或者直接启动
# 为了保险,尝试回到桌面重新进? 不,用户说“获取第一屏场站列表”,假设用户已经准备好了环境,或者我们手动进一下
# 为了全自动化,我们调用 Opener 进一下
# 但是 Opener 可能会重启微信,有点慢。
# 我们先判断当前包名,如果是微信,就默认在列表页(或者由用户手动滑到列表页)
# 用户指令暗示是交互式的:"获取第一屏...你去点击一下...停止程序"
# 所以我们假设当前就在列表页
current_app = d.app_current()
print(f"当前前台应用: {current_app.get('package')}")
if "com.tencent.mm" not in current_app.get('package', ''):
print("警告:微信似乎不在前台,请确保手机显示的是【驿来特】小程序列表页")
print("给你 5 秒钟调整手机屏幕...")
time.sleep(5)
else:
print("检测到微信在前台,准备截图...")
time.sleep(2) # 稍微等一下稳定
# 1. 获取第一屏场站列表,然后截图
timestamp = int(time.time())
list_screenshot_path = os.path.join(project_root, "Output", f"verify_step1_list_{timestamp}.jpg")
print(f"\n>>> [Step 1] 截图列表页: {list_screenshot_path}")
d.screenshot(list_screenshot_path)
# 2. 绿框标注,标识模拟点击点
print("\n>>> [Step 2] 识别卡片并标注...")
# 使用配置中的排除比例
cards = detect_cards_cv(list_screenshot_path, top_ratio=Setting.SAFE_EXCLUDE_RATIO, bottom_ratio=Setting.BOTTOM_SAFE_EXCLUDE_RATIO)
if not cards:
print("!!! [Error] 未检测到任何场站卡片,测试终止")
print(f"请检查截图: {list_screenshot_path}")
return
print(f"检测到 {len(cards)} 个卡片区域")
# 在图上绘制绿框和红点
debug_img = cv2.imread(list_screenshot_path)
if debug_img is None:
print("读取截图失败")
return
first_card = cards[0]
# 计算点击点:中心点
click_x = int((first_card[0] + first_card[2]) / 2)
click_y = int((first_card[1] + first_card[3]) / 2)
# 绘制所有卡片
for i, box in enumerate(cards):
# 绿框
cv2.rectangle(debug_img, (int(box[0]), int(box[1])), (int(box[2]), int(box[3])), (0, 255, 0), 2)
# 标号
cv2.putText(debug_img, str(i+1), (int(box[0]), int(box[1])+30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
# 绘制第一个卡片的点击点 (实心红圆)
cv2.circle(debug_img, (click_x, click_y), 15, (0, 0, 255), -1)
# 绘制同心圆
cv2.circle(debug_img, (click_x, click_y), 25, (0, 0, 255), 2)
marked_path = os.path.join(project_root, "Output", f"verify_step2_marked_{timestamp}.jpg")
cv2.imwrite(marked_path, debug_img)
print(f">>> 已生成标注图 (绿框+红点): {marked_path}")
print(f">>> 模拟点击目标: 第 1 个卡片, 坐标 ({click_x}, {click_y})")
# 计算点击前的 MD5
before_md5 = get_image_content_md5(list_screenshot_path, top_ratio=Setting.SAFE_EXCLUDE_RATIO, bottom_ratio=Setting.BOTTOM_SAFE_EXCLUDE_RATIO)
# 3. 你去点击一下,等一会
print(f"\n>>> [Step 3] 执行点击操作...")
# 使用 shell input tap
cmd = f"input tap {click_x} {click_y}"
print(f"执行命令: {cmd}")
d.shell(cmd)
print(">>> 点击完成,等待 5 秒让页面跳转...")
await asyncio.sleep(5)
# 4. 再继续截图,判断是否进入
after_screenshot_path = os.path.join(project_root, "Output", f"verify_step4_after_{timestamp}.jpg")
print(f"\n>>> [Step 4] 截图当前页面: {after_screenshot_path}")
d.screenshot(after_screenshot_path)
after_md5 = get_image_content_md5(after_screenshot_path, top_ratio=Setting.SAFE_EXCLUDE_RATIO, bottom_ratio=Setting.BOTTOM_SAFE_EXCLUDE_RATIO)
print("\n>>> [Step 5] 结果验证")
print("-" * 30)
print(f"点击前 MD5: {before_md5}")
print(f"点击后 MD5: {after_md5}")
if before_md5 != after_md5:
print(">>> [SUCCESS] 判定结果: 成功进入详情页! (MD5发生变化)")
else:
print(">>> [FAILURE] 判定结果: 未进入详情页 (MD5未变化)")
print("可能原因: 1. 点击无效 2. 页面加载极慢 3. 已经是详情页(误判)")
print("-" * 30)
if __name__ == "__main__":
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(run_verification())

View File

@@ -1,111 +0,0 @@
import sys
import os
import cv2
import numpy as np
# Add project root to path
project_root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
sys.path.append(project_root)
from Apps.YeLiTe.Kit import detect_cards_cv, read_image
def test_detection():
image_path = r"d:\dsWork\aiData\Output\list_1768309287.jpg"
if not os.path.exists(image_path):
print(f"Error: Image not found at {image_path}")
# Try to list files in Output to see what's available
output_dir = os.path.dirname(image_path)
if os.path.exists(output_dir):
print(f"Files in {output_dir}:")
for f in os.listdir(output_dir):
print(f)
return
print(f"Testing detection on {image_path}")
# Debug mode: copy logic from Kit.py but add debug prints and saves
img = read_image(image_path)
if img is None: return
h, w = img.shape[:2]
print(f"Image size: {w}x{h}")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
# Try different thresholds
edges = cv2.Canny(blurred, 10, 50) # Lower thresholds
# Save edges
debug_edges_path = os.path.join(os.path.dirname(__file__), "debug_edges.jpg")
cv2.imencode('.jpg', edges)[1].tofile(debug_edges_path)
print(f"Saved edges to {debug_edges_path}")
contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
print(f"Found {len(contours)} contours")
# Draw all contours on a debug image
debug_contours_img = img.copy()
cv2.drawContours(debug_contours_img, contours, -1, (0, 0, 255), 1)
debug_contours_path = os.path.join(os.path.dirname(__file__), "debug_contours.jpg")
cv2.imencode('.jpg', debug_contours_img)[1].tofile(debug_contours_path)
print(f"Saved all contours to {debug_contours_path}")
min_card_width = int(w * 0.8)
print(f"Min card width (strict): {min_card_width}")
for i, cnt in enumerate(contours):
x, y, cw, ch = cv2.boundingRect(cnt)
if cw > 100 and ch > 50: # Only print somewhat large ones
print(f"Contour {i}: pos=({x},{y}), size={cw}x{ch}, aspect_ratio={cw/ch:.2f}")
# Run actual detection
try:
cards = detect_cards_cv(image_path)
print(f"Detected {len(cards)} cards")
except Exception as e:
print(f"Error during detection: {e}")
import traceback
traceback.print_exc()
return
# Read image for drawing
img_lv = read_image(image_path)
img_flag = read_image(image_path)
if img_lv is None:
print("Failed to read image")
return
for i, card in enumerate(cards):
x1, y1, x2, y2 = card
print(f"Card {i+1}: [{x1}, {y1}, {x2}, {y2}]")
# Draw green rectangle on img_lv
cv2.rectangle(img_lv, (x1, y1), (x2, y2), (0, 255, 0), 2)
cv2.putText(img_lv, f"Card {i+1}", (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
# Calculate click point (center)
center_x = (x1 + x2) // 2
center_y = (y1 + y2) // 2
# Draw red click point on img_flag
cv2.circle(img_flag, (center_x, center_y), 5, (0, 0, 255), -1)
# Also draw a crosshair for better visibility
cv2.line(img_flag, (center_x - 10, center_y), (center_x + 10, center_y), (0, 0, 255), 1)
cv2.line(img_flag, (center_x, center_y - 10), (center_x, center_y + 10), (0, 0, 255), 1)
cv2.putText(img_flag, f"Click {i+1}", (center_x + 10, center_y), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 1)
print(f"Click Point {i+1}: ({center_x}, {center_y})")
# Save _lv.jpg
base_name = os.path.splitext(os.path.basename(image_path))[0]
output_lv = os.path.join(os.path.dirname(__file__), f"{base_name}_lv.jpg")
cv2.imencode('.jpg', img_lv)[1].tofile(output_lv)
print(f"Green box image saved to {output_lv}")
# Save _flag.jpg
output_flag = os.path.join(os.path.dirname(__file__), f"{base_name}_flag.jpg")
cv2.imencode('.jpg', img_flag)[1].tofile(output_flag)
print(f"Click point image saved to {output_flag}")
if __name__ == "__main__":
test_detection()