from playwright.sync_api import sync_playwright
import os
import time

IMAGE_PATH = os.path.abspath("test.jpg")

with sync_playwright() as p:
    browser = p.chromium.launch(headless=False)
    context = browser.new_context(storage_state="xhs_state.json")
    page = context.new_page()

    page.goto("https://creator.xiaohongshu.com/publish/publish")
    time.sleep(5)

    # ===== 精确切换到图文模式 =====
    switched = False

    for frame in page.frames:
        try:
            tabs = frame.locator("text=上传图文")
            if tabs.count() > 0:
                print("找到上传图文tab")
                tabs.first.click()
                time.sleep(2)
                switched = True
                break
        except:
            pass

    if switched:
        print("已确保图文模式")
    else:
        print("未找到图文tab（可能默认已是图文）")

    # ===== 触发上传 =====
    uploaded = False

    for frame in page.frames:
        try:
            upload_button = frame.locator("text=点击上传")
            if upload_button.count() > 0:
                print("找到上传按钮")

                with page.expect_file_chooser() as fc_info:
                    upload_button.first.click()

                file_chooser = fc_info.value
                file_chooser.set_files(IMAGE_PATH)

                uploaded = True
                break
        except:
            pass

    if not uploaded:
        print("未找到上传按钮")

    print("观察是否出现图片缩略图")
    input("按回车关闭...")

    browser.close()
