获取微信通讯录好友的rpa


import uiautomation as auto
import time
import csv
import os

# ======== 辅助函数 ========
def move_to_rect_center(control):
    """将鼠标移动到控件中心"""
    rect = control.BoundingRectangle
    x = (rect.left + rect.right) // 2
    y = (rect.top + rect.bottom) // 2
    auto.MoveTo(x, y)
    return (x, y)

def find_all_contacts(window, max_depth=7):
    """递归查找所有联系人行"""
    result = []
    queue = [(window, 0)]
    while queue:
        node, depth = queue.pop(0)
        if node.ControlTypeName == 'ListItemControl' and node.ClassName == 'mmui::ContactsManagerDetailCell':
            result.append(node)
        if depth < max_depth:
            try:
                for child in node.GetChildren():
                    queue.append((child, depth + 1))
            except Exception:
                continue
    return result


# ======== 打开通讯录管理窗口 ========
wechat = auto.WindowControl(searchDepth=1, className='WeChatMainWndForPC', Name='微信')
wechat.SetActive()
time.sleep(0.8)

tab_contact = wechat.ButtonControl(Name='通讯录')
tab_contact.Click()
time.sleep(1.0)

manager_btn = wechat.ListItemControl(ClassName='mmui::ContactsCellMangerBtnView')
if not manager_btn.Exists(maxSearchSeconds=5):
    manager_btn = wechat.Control(searchDepth=10, ClassName='mmui::ContactsCellMangerBtnView')
if not manager_btn.Exists(maxSearchSeconds=5):
    raise LookupError("未找到 '通讯录管理' 按钮,请确认当前在通讯录界面。")

manager_btn.Click(simulateMove=True)
time.sleep(1.5)

# ======== 获取通讯录管理窗口 ========
cm = auto.WindowControl(Name="通讯录管理", ClassName="mmui::ContactsManagerWindow")
if not cm.Exists(maxSearchSeconds=5):
    raise LookupError("已点击通讯录管理,但窗口未出现。")

cm.SetActive()
time.sleep(0.6)

# ======== 定位第一个联系人 ========
first_contact = find_all_contacts(cm)
if not first_contact:
    print("未检测到联系人,等待加载中...")
    time.sleep(2)
    first_contact = find_all_contacts(cm)

if first_contact:
    x, y = move_to_rect_center(first_contact[0])  # 将鼠标移到第一个联系人
else:
    x, y = move_to_rect_center(cm)  # 如果没有找到联系人,默认移动到窗口中间
print(f"鼠标已移到第一个联系人区域中心 ({x}, {y})")

# ======== 滚动并提取联系人 ========
contacts = []
seen = set()
b = 1
no_new_rounds = 0
start_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
print(f"
开始时间:{start_time}
")

hard_timeout = 180
t0 = time.time()

while True:
    if time.time() - t0 > hard_timeout:
        print("超时,自动停止。")
        break

    items = find_all_contacts(cm)
    new_count = 0
    for item in items:
        name = (item.Name or '').strip()
        if name and name not in seen:
            seen.add(name)
            contacts.append(name)
            print(f"{b}. {name}")
            b += 1
            new_count += 1

    if new_count == 0:
        no_new_rounds += 1
    else:
        no_new_rounds = 0

    if no_new_rounds >= 3:
        print("检测到底部,停止采集。")
        break

    for _ in range(3):
        auto.WheelDown()
        time.sleep(0.3)

# ======== 输出与保存 ========
save_path = os.path.join(os.getcwd(), "wechat_contacts.csv")
with open(save_path, "w", newline='', encoding="utf-8-sig") as f:
    writer = csv.writer(f)
    writer.writerow(["序号", "联系人名称"])
    for i, name in enumerate(contacts, start=1):
        writer.writerow([i, name])

print("
==== 通讯录采集完成 ====")
print(f"共获取 {len(contacts)} 个联系人")
print(f"结果已保存到: {save_path}")

© 版权声明

相关文章

暂无评论

您必须登录才能参与评论!
立即登录
none
暂无评论...