mytest.py 2.55 KB
from playwright.sync_api import sync_playwright
import asyncio

import asyncio
import json
from playwright.async_api import async_playwright, expect


async def write_cookies_to_file(cookies, file_path):

    with open(file_path, 'w') as f:
        json.dump(cookies, f)


async def read_cookies_from_file(file_path):
    try:
        with open(file_path, 'r') as f:
            return json.load(f)
    except FileNotFoundError:
        return []


async def main():
    filePath = "/Users/rinal/Downloads/xhs.json"
    async with async_playwright() as p:
        browser = await p.chromium.launch(headless=False)
        context = await browser.new_context()
        page = await context.new_page()
        await page.goto("https://www.xiaohongshu.com")
        print(await page.title()) # login-container
        await page.wait_for_selector("div.link-wrapper a.link-wrapper span.channel")

        await asyncio.sleep(3)
        cookies = await context.cookies()
        print(cookies)
        await write_cookies_to_file(cookies, filePath)

        await browser.close()


async def upload():
    filePath = "/Users/rinal/Downloads/xhs.json"
    print(filePath)
    async with async_playwright() as p:
        browser = await p.chromium.launch()
        context = await browser.new_context()
        page = await context.new_page()
        saved_cookies = await read_cookies_from_file(filePath)
        await context.add_cookies(saved_cookies)
        await page.goto("https://www.xiaohongshu.com")  # 再次访问对应网址,此时带着之前保存的cookie
        await page.wait_for_selector("div.link-wrapper a.link-wrapper span.channel")
        await page.goto("https://creator.xiaohongshu.com/publish/publish?source=official")
        await page.locator("input.upload-input").set_input_files(
            "/Users/rinal/PycharmProjects/xj-marketing/videos/huahua.mp4")
        button_elem = page.locator('button div span:has-text("发布")')
        await button_elem.wait_for(state='visible')  # 确保按钮可见

        await page.locator("div.titleInput div div input").fill("花花")
        tags = ['花花', '熊猫']
        inputTag = page.locator('id=quillEditor').locator('div p')
        await inputTag.click()
        for index, tag in enumerate(tags, start=1):
            await page.keyboard.type(f"#{tag} ")
            await asyncio.sleep(2)

        print("已写完tag")
        await asyncio.sleep(10)
        await button_elem.click()

        await page.wait_for_selector('p:has-text("发布成功")')

    await browser.close()


# asyncio.run(main())
asyncio.run(upload())

#