mytest.py
2.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
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())
#