返回 Social Auto Upload
main.py
1 # -*- coding: utf-8 -*-
2 import re
3 from datetime import datetime
4
5 from playwright.async_api import Playwright, async_playwright
6 import os
7 import asyncio
8 from uploader.tk_uploader.tk_config import Tk_Locator
9 from utils.base_social_media import set_init_script
10 from utils.files_times import get_absolute_path
11 from utils.log import tiktok_logger
12 from conf import LOCAL_CHROME_HEADLESS
13
14
15 async def cookie_auth(account_file):
16 async with async_playwright() as playwright:
17 browser = await playwright.firefox.launch(headless=LOCAL_CHROME_HEADLESS)
18 context = await browser.new_context(storage_state=account_file)
19 context = await set_init_script(context)
20 # 创建一个新的页面
21 page = await context.new_page()
22 # 访问指定的 URL
23 await page.goto("https://www.tiktok.com/tiktokstudio/upload?lang=en")
24 await page.wait_for_load_state('networkidle')
25 try:
26 # 选择所有的 select 元素
27 select_elements = await page.query_selector_all('select')
28 for element in select_elements:
29 class_name = await element.get_attribute('class')
30 # 使用正则表达式匹配特定模式的 class 名称
31 if re.match(r'tiktok-.*-SelectFormContainer.*', class_name):
32 tiktok_logger.error("[+] cookie expired")
33 return False
34 tiktok_logger.success("[+] cookie valid")
35 return True
36 except:
37 tiktok_logger.success("[+] cookie valid")
38 return True
39
40
41 async def tiktok_setup(account_file, handle=False):
42 account_file = get_absolute_path(account_file, "tk_uploader")
43 if not os.path.exists(account_file) or not await cookie_auth(account_file):
44 if not handle:
45 return False
46 tiktok_logger.info('[+] cookie file is not existed or expired. Now open the browser auto. Please login with your way(gmail phone, whatever, the cookie file will generated after login')
47 await get_tiktok_cookie(account_file)
48 return True
49
50
51 async def get_tiktok_cookie(account_file):
52 async with async_playwright() as playwright:
53 options = {
54 'args': [
55 '--lang en-GB',
56 ],
57 'headless': LOCAL_CHROME_HEADLESS, # Set headless option here
58 }
59 # Make sure to run headed.
60 browser = await playwright.firefox.launch(**options)
61 # Setup context however you like.
62 context = await browser.new_context() # Pass any options
63 context = await set_init_script(context)
64 # Pause the page, and start recording manually.
65 page = await context.new_page()
66 await page.goto("https://www.tiktok.com/login?lang=en")
67 await page.pause()
68 # 点击调试器的继续,保存cookie
69 await context.storage_state(path=account_file)
70
71
72 class TiktokVideo(object):
73 def __init__(self, title, file_path, tags, publish_date, account_file):
74 self.title = title
75 self.file_path = file_path
76 self.tags = tags
77 self.publish_date = publish_date
78 self.account_file = account_file
79 self.headless = LOCAL_CHROME_HEADLESS
80 self.locator_base = None
81
82
83 async def set_schedule_time(self, page, publish_date):
84 schedule_input_element = self.locator_base.get_by_label('Schedule')
85 await schedule_input_element.wait_for(state='visible') # 确保按钮可见
86
87 await schedule_input_element.click()
88 scheduled_picker = self.locator_base.locator('div.scheduled-picker')
89 await scheduled_picker.locator('div.TUXInputBox').nth(1).click()
90
91 calendar_month = await self.locator_base.locator('div.calendar-wrapper span.month-title').inner_text()
92
93 n_calendar_month = datetime.strptime(calendar_month, '%B').month
94
95 schedule_month = publish_date.month
96
97 if n_calendar_month != schedule_month:
98 if n_calendar_month < schedule_month:
99 arrow = self.locator_base.locator('div.calendar-wrapper span.arrow').nth(-1)
100 else:
101 arrow = self.locator_base.locator('div.calendar-wrapper span.arrow').nth(0)
102 await arrow.click()
103
104 # day set
105 valid_days_locator = self.locator_base.locator(
106 'div.calendar-wrapper span.day.valid')
107 valid_days = await valid_days_locator.count()
108 for i in range(valid_days):
109 day_element = valid_days_locator.nth(i)
110 text = await day_element.inner_text()
111 if text.strip() == str(publish_date.day):
112 await day_element.click()
113 break
114 # time set
115 await scheduled_picker.locator('div.TUXInputBox').nth(0).click()
116
117 hour_str = publish_date.strftime("%H")
118 correct_minute = int(publish_date.minute / 5)
119 minute_str = f"{correct_minute:02d}"
120
121 hour_selector = f"span.tiktok-timepicker-left:has-text('{hour_str}')"
122 minute_selector = f"span.tiktok-timepicker-right:has-text('{minute_str}')"
123
124 # pick hour first
125 await self.locator_base.locator(hour_selector).click()
126 # click time button again
127 # 等待某个特定的元素出现或状态变化,表明UI已更新
128 await page.wait_for_timeout(1000) # 等待500毫秒
129 await scheduled_picker.locator('div.TUXInputBox').nth(0).click()
130 # pick minutes after
131 await self.locator_base.locator(minute_selector).click()
132
133 # click title to remove the focus.
134 await self.locator_base.locator("h1:has-text('Upload video')").click()
135
136 async def handle_upload_error(self, page):
137 tiktok_logger.info("video upload error retrying.")
138 select_file_button = self.locator_base.locator('button[aria-label="Select file"]')
139 async with page.expect_file_chooser() as fc_info:
140 await select_file_button.click()
141 file_chooser = await fc_info.value
142 await file_chooser.set_files(self.file_path)
143
144 async def upload(self, playwright: Playwright) -> None:
145 browser = await playwright.firefox.launch(headless=self.headless)
146 context = await browser.new_context(storage_state=f"{self.account_file}")
147 context = await set_init_script(context)
148 page = await context.new_page()
149
150 await page.goto("https://www.tiktok.com/creator-center/upload")
151 tiktok_logger.info(f'[+]Uploading-------{self.title}.mp4')
152
153 await page.wait_for_url("https://www.tiktok.com/tiktokstudio/upload", timeout=10000)
154
155 try:
156 await page.wait_for_selector('iframe[data-tt="Upload_index_iframe"], div.upload-container', timeout=10000)
157 tiktok_logger.info("Either iframe or div appeared.")
158 except Exception as e:
159 tiktok_logger.error("Neither iframe nor div appeared within the timeout.")
160
161 await self.choose_base_locator(page)
162
163 upload_button = self.locator_base.locator(
164 'button:has-text("Select video"):visible')
165 await upload_button.wait_for(state='visible') # 确保按钮可见
166
167 async with page.expect_file_chooser() as fc_info:
168 await upload_button.click()
169 file_chooser = await fc_info.value
170 await file_chooser.set_files(self.file_path)
171
172 await self.add_title_tags(page)
173 # detact upload status
174 await self.detect_upload_status(page)
175 if self.publish_date != 0:
176 await self.set_schedule_time(page, self.publish_date)
177
178 await self.click_publish(page)
179
180 await context.storage_state(path=f"{self.account_file}") # save cookie
181 tiktok_logger.info(' [-] update cookie!')
182 await asyncio.sleep(2) # close delay for look the video status
183 # close all
184 await context.close()
185 await browser.close()
186
187 async def add_title_tags(self, page):
188
189 editor_locator = self.locator_base.locator('div.public-DraftEditor-content')
190 await editor_locator.click()
191
192 await page.keyboard.press("End")
193
194 await page.keyboard.press("Control+A")
195
196 await page.keyboard.press("Delete")
197
198 await page.keyboard.press("End")
199
200 await page.wait_for_timeout(1000) # 等待1秒
201
202 await page.keyboard.insert_text(self.title)
203 await page.wait_for_timeout(1000) # 等待1秒
204 await page.keyboard.press("End")
205
206 await page.keyboard.press("Enter")
207
208 # tag part
209 for index, tag in enumerate(self.tags, start=1):
210 tiktok_logger.info("Setting the %s tag" % index)
211 await page.keyboard.press("End")
212 await page.wait_for_timeout(1000) # 等待1秒
213 await page.keyboard.insert_text("#" + tag + " ")
214 await page.keyboard.press("Space")
215 await page.wait_for_timeout(1000) # 等待1秒
216
217 await page.keyboard.press("Backspace")
218 await page.keyboard.press("End")
219
220 async def click_publish(self, page):
221 success_flag_div = '#\\:r9\\:'
222 while True:
223 try:
224 publish_button = self.locator_base.locator('div.btn-post')
225 if await publish_button.count():
226 await publish_button.click()
227
228 await self.locator_base.locator(success_flag_div).wait_for(state="visible", timeout=3000)
229 tiktok_logger.success(" [-] video published success")
230 break
231 except Exception as e:
232 if await self.locator_base.locator(success_flag_div).count():
233 tiktok_logger.success(" [-]video published success")
234 break
235 else:
236 tiktok_logger.exception(f" [-] Exception: {e}")
237 tiktok_logger.info(" [-] video publishing")
238 await page.screenshot(full_page=True)
239 await asyncio.sleep(0.5)
240
241 async def detect_upload_status(self, page):
242 while True:
243 try:
244 if await self.locator_base.locator('div.btn-post > button').get_attribute("disabled") is None:
245 tiktok_logger.info(" [-]video uploaded.")
246 break
247 else:
248 tiktok_logger.info(" [-] video uploading...")
249 await asyncio.sleep(2)
250 if await self.locator_base.locator('button[aria-label="Select file"]').count():
251 tiktok_logger.info(" [-] found some error while uploading now retry...")
252 await self.handle_upload_error(page)
253 except:
254 tiktok_logger.info(" [-] video uploading...")
255 await asyncio.sleep(2)
256
257 async def choose_base_locator(self, page):
258 # await page.wait_for_selector('div.upload-container')
259 if await page.locator('iframe[data-tt="Upload_index_iframe"]').count():
260 self.locator_base = self.locator_base
261 else:
262 self.locator_base = page.locator(Tk_Locator.default)
263
264 async def main(self):
265 async with async_playwright() as playwright:
266 await self.upload(playwright)
267
268
268 lines PYTHON