返回 Social Auto Upload
upload_video_to_xhs.py
根目录 / examples / upload_video_to_xhs.py
1 import configparser
2 from pathlib import Path
3 from time import sleep
4
5 from xhs import XhsClient
6
7 from conf import BASE_DIR
8 from utils.files_times import generate_schedule_time_next_day, get_title_and_hashtags
9 from uploader.xhs_uploader.main import sign_local, beauty_print
10
11 config = configparser.RawConfigParser()
12 config.read(Path(BASE_DIR / "uploader" / "xhs_uploader" / "accounts.ini"))
13
14
15 if __name__ == '__main__':
16 filepath = Path(BASE_DIR) / "videos"
17 # 获取视频目录
18 folder_path = Path(filepath)
19 # 获取文件夹中的所有文件
20 files = list(folder_path.glob("*.mp4"))
21 file_num = len(files)
22
23 cookies = config['account1']['cookies']
24 xhs_client = XhsClient(cookies, sign=sign_local, timeout=60)
25 # auth cookie
26 # 注意:该校验cookie方式可能并没那么准确
27 try:
28 xhs_client.get_video_first_frame_image_id("3214")
29 except:
30 print("cookie 失效")
31 exit()
32
33 publish_datetimes = generate_schedule_time_next_day(file_num, 1, daily_times=[16])
34
35 for index, file in enumerate(files):
36 title, tags = get_title_and_hashtags(str(file))
37 # 加入到标题 补充标题(xhs 可以填1000字不写白不写)
38 tags_str = ' '.join(['#' + tag for tag in tags])
39 hash_tags_str = ''
40 hash_tags = []
41
42 # 打印视频文件名、标题和 hashtag
43 print(f"视频文件名:{file}")
44 print(f"标题:{title}")
45 print(f"Hashtag:{tags}")
46
47 topics = []
48 # 获取hashtag
49 for i in tags[:3]:
50 topic_official = xhs_client.get_suggest_topic(i)
51 if topic_official:
52 topic_official[0]['type'] = 'topic'
53 topic_one = topic_official[0]
54 hash_tag_name = topic_one['name']
55 hash_tags.append(hash_tag_name)
56 topics.append(topic_one)
57
58 hash_tags_str = ' ' + ' '.join(['#' + tag + '[话题]#' for tag in hash_tags])
59
60 note = xhs_client.create_video_note(title=title[:20], video_path=str(file),
61 desc=title + tags_str + hash_tags_str,
62 topics=topics,
63 is_private=False,
64 post_time=publish_datetimes[index].strftime("%Y-%m-%d %H:%M:%S"))
65
66 beauty_print(note)
67 # 强制休眠30s,避免风控(必要)
68 sleep(30)
69
69 lines PYTHON