background
Study Python+Selenium Automated testing framework , Simple implementation Mac Next automatic batch upload video watermelon video and release , Share with students in need ( Not doing too much exception handling ).
Script implementation
- First, log in through the manual mobile phone number , Save watermelon video website cookie file
- After loading cookie Content , Use scripts to upload videos in bulk , Save to draft ( It can also be published automatically , For secondary editing , Such as changing the cover )
- Finally, by traversing the video draft list , To post a draft video
PS: When you upload or post too many videos on the same day , Will be limited by watermelon video .
Installation dependency
# Installation dependency
$ pip install selenium PyKeyboard PyMouse pyperclip
# install chromedriver
$ brew install chromedriver
The script content
#!/usr/bin/python
# -*- coding: utf-8 -*-
import time
import json
import os
import shutil
import sys
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver import ActionChains
from pykeyboard import PyKeyboard
from pymouse import PyMouse
import pyperclip
class XiGua:
"""
Mac Watermelon video automatically upload video and release draft
"""
def __init__(self):
"""
initialization , Open the browser
"""
self.driver = webdriver.Chrome()
def save_cookies(self, cookies_file_name):
"""
preservation cookies
cookies_file_name: cookies File name
"""
# reserve 20 second , To log in manually
time.sleep(20)
# After successful login , preservation cookies file
with open(cookies_file_name, 'w') as cookies_file:
cookies_file.write(json.dumps(self.driver.get_cookies()))
def load_cookies(self, cookies_file_name):
"""
load cookie
cookies_file_name: cookies File name
"""
# load cookies file
with open(cookies_file_name, 'r') as cookies_file:
cookies_list = json.load(cookies_file)
for cookie in cookies_list:
if 'expiry' in cookie:
del cookie['expiry']
self.driver.add_cookie(cookie)
# load cookie after , Refresh page takes effect
self.driver.refresh()
def is_exist_element_by_xpath(self, xpath):
"""
Determine whether an element exists
"""
flag = True
try:
self.driver.find_element_by_xpath(xpath)
return flag
except Exception as e:
flag = False
print("xpath: [%s] The element of does not exist , error :%s" % xpath, e)
return flag
def upload_video(self, video_file_path):
"""
Upload video
video_file_path: Upload video path
"""
# Open the upload video page
self.driver.get("https://studio.ixigua.com/upload?from=post_article")
# Click upload
self.driver.find_element_by_class_name("byte-upload-trigger-drag").click()
time.sleep(5)
# Choose a video file
k = PyKeyboard()
m = PyMouse()
# open
k.press_keys(['Command', 'Shift', 'G'])
x_dim, y_dim = m.screen_size()
k.press_keys(['Shift'])
m.click(x_dim // 2, y_dim // 2, 1)
# Copy video file path
pyperclip.copy(video_file_path)
# Paste
k.press_keys(['Command', 'V'])
time.sleep(2)
k.press_key('Return')
time.sleep(2)
k.press_key('Return')
time.sleep(2)
# Set reprint options
self.driver.find_element_by_xpath(
'//*[@id="js-video-list-content"]/div/div[2]/div[4]/div[2]/div/div/label[2]/span/span').click()
time.sleep(1)
# Tiktok
# self.driver.find_element_by_class_name("byte-checkbox-mask").click()
# Loop judgment video upload success , Waiting for failure 10 Seconds later , Judge again , Until success
while ' Upload successful ' not in self.driver.find_element_by_xpath(
'//*[@id="js-video-list-content"]/div/div[1]/div[1]/div[2]/div[2]').text:
print(" Loop waiting for video upload to succeed , wait for 10 second ")
time.sleep(10)
# Set video cover
self.driver.find_element_by_class_name("m-xigua-upload").click()
print(' Click on - Upload the cover ')
time.sleep(5)
try:
reload = self.driver.find_element_by_xpath('/html/body/div[3]/div/div[2]/div/div[1]/div/div/div/div[2]')
# Video cover parsing failure processing , Loop refresh
if reload != '':
print(' Video cover parsing failure processing , Start a loop refresh ')
while XiGua.is_exist_element_by_xpath(self,
'/html/body/div[3]/div/div[2]/div/div[1]/div/div/div/div[2]'):
# Click loop
self.driver.find_element_by_xpath(
'/html/body/div[3]/div/div[2]/div/div[1]/div/div/div/div[2]').click()
print(' After refresh failed , wait for 5 second , Refresh again ')
time.sleep(5)
# Choose the first picture
img = self.driver.find_element_by_xpath('/html/body/div[3]/div/div[2]/div/div[1]/div/div/div[1]/img')
img.click()
except Exception as e:
print(' The cover resolution is normal , No need to refresh ')
pass
# next step
cover_next_element = WebDriverWait(self.driver, 30).until(
lambda x: x.find_element_by_xpath(
'/html/body/div[3]/div/div[2]/div/div[2]/div')
)
cover_next_element.click()
print(' Click on - The next step on the cover ')
try:
# Finish cutting
cover_crop_element = WebDriverWait(self.driver, 30).until(
lambda x: x.find_element_by_xpath(
'//*[@id="tc-ie-base-content"]/div[2]/div[2]/div[2]/div/div[2]/div/div/div[2]')
)
if cover_crop_element != '':
cover_crop_element.click()
print(' Click on - The cover is cut ')
else:
print(' There's no need to cut the cover ')
except Exception as e:
print(' Abnormal cutting cover :%s' % e)
pass
time.sleep(5)
# determine
self.driver.find_element_by_xpath('//*[@id="tc-ie-base-content"]/div[2]/div[2]/div[3]/div[3]/button[2]').click()
print(' Click on - Cover confirmed ')
time.sleep(1)
# Confirm again
self.driver.find_element_by_xpath('/html/body/div[4]/div/div[2]/div/div[2]/button[2]').click()
print(' Click on - Cover confirmed again ')
time.sleep(5)
# Save Draft
draft_element = WebDriverWait(self.driver, 30).until(
lambda x: x.find_element_by_xpath('//*[@id="js-submit-draft-0"]/button')
)
action = ActionChains(self.driver)
print(' Click on - Save draft ')
# Move the scroll bar to the bottom
js = "window.scrollTo(0,document.body.scrollHeight)"
self.driver.execute_script(js)
# Move to Save Draft Button click
action.move_to_element(draft_element).click().perform()
def close(self):
"""
Close the browser
"""
self.driver.close()
def batch_upload(self, videos_dir_path):
"""
Bulk upload video
videos_dir_path: Upload video storage path
"""
files = os.listdir(videos_dir_path)
# Upload in descending order , When the draft is published , The video sequence number is in order
files.sort(reverse=True)
# Bulk upload video
for file in files:
if os.path.splitext(file)[1] == '.mp4':
full_file_path = os.path.join(videos_dir_path, os.path.splitext(file)[0])
print("== Start uploading video :%s" % full_file_path)
self.upload_video(full_file_path)
src = os.path.join(videos_dir_path, file)
dst = os.path.join(videos_dir_path, 'bak', file)
# After publishing , Move to the backup directory
shutil.move(src, dst)
def videos_release(self):
"""
Draft video release
"""
self.driver.get("https://studio.ixigua.com/content")
time.sleep(2)
# Click on the draft to navigate
draft_navigation_element = WebDriverWait(self.driver, 30).until(
lambda x: x.find_element_by_xpath('//*[@id="app"]/div/section/div/div[1]/ul/li[3]')
)
draft_navigation_element.click()
print(' Click on - Draft navigation ')
time.sleep(2)
# Draft list
draft_elements = self.driver.find_elements_by_class_name('content-card__title ')
# The draft list is empty , The exit
if len(draft_elements) == 0:
print(" The draft list is empty ")
XiGua.close(self)
sys.exit()
# Circular release draft , Every time you post the first
for i in range(1, 99999):
# The draft list is empty , sign out
if draft_elements == '':
print(' Draft release completed , in total :%s' % str(i))
XiGua.close(self)
sys.exit()
print(' Number of current releases %s, Release video : %s' % (str(i), draft_elements[0].text))
# Release draft first video
draft_elements[0].click()
time.sleep(3)
# Publish now
element2 = WebDriverWait(self.driver, 30).until(
lambda x: x.find_element_by_xpath('//button[contains(text(), " Release ")]')
)
element2.click()
print(' Click on - Video release ')
# Determine whether publishing failed , If the title is too long
try:
# Error handling
if XiGua.is_exist_element_by_xpath(self, '/html/body/div[3]/div/div/div/span'):
print(' Error in Publishing , sign out , Please check the error , For example, the title is too long ')
sys.exit()
except Exception as e:
print(' Draft release exception :%s' % e)
pass
# Handle cover resolution low prompt
try:
# Cover resolution is low
cover_cancel_element = self.driver.find_element_by_xpath('//div[contains(text(), " Cancel ")]')
print(' Cover resolution low processing , Cancel... Directly ')
# Error handling
if cover_cancel_element != '':
print(' Remove cover resolution low ')
cover_cancel_element.click()
# Publish now
cover_publish_element = WebDriverWait(self.driver, 30).until(
lambda x: x.find_element_by_xpath('//button[contains(text(), " Release ")]')
)
cover_publish_element.click()
except Exception as e:
print(' Cover resolution is low, abnormal :%s' % e)
pass
# Click on the draft
draft_publish_element = WebDriverWait(self.driver, 30).until(
lambda x: x.find_element_by_xpath('//*[@id="app"]/div/section/div/div[1]/ul/li[3]')
)
draft_publish_element.click()
time.sleep(2)
print(' Retrieve draft list again ')
draft_elements = self.driver.find_elements_by_class_name('content-card__title ')
print(draft_elements)
def xigua_videos_release(self, base_url, cookies_file_path):
"""
Watermelon video release draft
base_url: Watermelon video website
cookies_file_path: Watermelon Video cookies File path
"""
self.driver.get(base_url)
# load cookies
XiGua.load_cookies(self, cookies_file_path)
# Draft release video
XiGua.videos_release(self)
# Close the browser
XiGua.close(self)
def xigua_batch_upload(self, base_url, cookies_file_path, videos_dir_path):
"""
Watermelon video batch release video
base_url: Watermelon video website
cookies_file_path: Watermelon Video cookies File path
videos_dir_path: Upload video storage path
"""
self.driver.get(base_url)
XiGua.load_cookies(self, cookies_file_path)
XiGua.batch_upload(self, videos_dir_path)
XiGua.close(self)
def xigua_save_cookies(self, base_url, cookies_file_path):
"""
Watermelon video release draft
base_url: Web site address
cookies_file_path: Website cookies File path
"""
self.driver.get(base_url)
# preservation cookies
XiGua.save_cookies(self, cookies_file_path)
XiGua.close(self)
if __name__ == '__main__':
xi_gua = XiGua()
# Watermelon Video
base_url = 'https://www.ixigua.com/'
xigua_cookies = '/tmp/xigua_update_video/xigua_cookies.txt'
videos_dir_path = '/tmp/rm'
## 1. preservation cookie
# xi_gua.xigua_save_cookies(base_url, 'xigua_cookies.txt')
## 2. Batch upload
xi_gua.xigua_batch_upload(base_url, xigua_cookies, videos_dir_path)
## 3. Mass release drafts
# xi_gua.xigua_videos_release(base_url, xigua_cookies)
WeChat official account :daodaotest