Automatic upload and draft release of watermelon video using Python + selenium on MAC

Jiang Liheng 2020-11-12 22:23:44
automatic upload draft release watermelon


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

  1. First, log in through the manual mobile phone number , Save watermelon video website cookie file
  2. 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 )
  3. 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

# -*- coding: utf-8 -*-
import time
import json
import os
import shutil
import sys
from selenium import webdriver
from 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
# After successful login , preservation cookies file
with open(cookies_file_name, 'w') as cookies_file:
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']
# load cookie after , Refresh page takes effect
def is_exist_element_by_xpath(self, xpath):
Determine whether an element exists
flag = True
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
# Click upload
# 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']) // 2, y_dim // 2, 1)
# Copy video file path
# Paste
k.press_keys(['Command', 'V'])
# Set reprint options
# 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(
print(" Loop waiting for video upload to succeed , wait for 10 second ")
# Set video cover
print(' Click on - Upload the cover ')
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,
# Click loop
print(' After refresh failed , wait for 5 second , Refresh again ')
# 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')
except Exception as e:
print(' The cover resolution is normal , No need to refresh ')
# next step
cover_next_element = WebDriverWait(self.driver, 30).until(
lambda x: x.find_element_by_xpath(
print(' Click on - The next step on the cover ')
# Finish cutting
cover_crop_element = WebDriverWait(self.driver, 30).until(
lambda x: x.find_element_by_xpath(
if cover_crop_element != '':
print(' Click on - The cover is cut ')
print(' There's no need to cut the cover ')
except Exception as e:
print(' Abnormal cutting cover :%s' % e)
# determine
print(' Click on - Cover confirmed ')
# Confirm again
print(' Click on - Cover confirmed again ')
# 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)"
# Move to Save Draft Button click
def close(self):
Close the browser
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
# 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)
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
# 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]')
print(' Click on - Draft navigation ')
# 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 ")
# 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))
print(' Number of current releases %s, Release video : %s' % (str(i), draft_elements[0].text))
# Release draft first video
# Publish now
element2 = WebDriverWait(self.driver, 30).until(
lambda x: x.find_element_by_xpath('//button[contains(text(), " Release ")]')
print(' Click on - Video release ')
# Determine whether publishing failed , If the title is too long
# 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 ')
except Exception as e:
print(' Draft release exception :%s' % e)
# Handle cover resolution low prompt
# 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 ')
# Publish now
cover_publish_element = WebDriverWait(self.driver, 30).until(
lambda x: x.find_element_by_xpath('//button[contains(text(), " Release ")]')
except Exception as e:
print(' Cover resolution is low, abnormal :%s' % e)
# 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]')
print(' Retrieve draft list again ')
draft_elements = self.driver.find_elements_by_class_name('content-card__title ')
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
# load cookies
XiGua.load_cookies(self, cookies_file_path)
# Draft release video
# Close the browser
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
XiGua.load_cookies(self, cookies_file_path)
XiGua.batch_upload(self, videos_dir_path)
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
# preservation cookies
XiGua.save_cookies(self, cookies_file_path)
if __name__ == '__main__':
xi_gua = XiGua()
# Watermelon Video
base_url = ''
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

本文为[Jiang Liheng]所创,转载请带上原文链接,感谢

  1. 利用Python爬虫获取招聘网站职位信息
  2. Using Python crawler to obtain job information of recruitment website
  3. Several highly rated Python libraries arrow, jsonpath, psutil and tenacity are recommended
  4. Python装饰器
  5. Python实现LDAP认证
  6. Python decorator
  7. Implementing LDAP authentication with Python
  8. Vscode configures Python development environment!
  9. In Python, how dare you say you can't log module? ️
  10. 我收藏的有关Python的电子书和资料
  11. python 中 lambda的一些tips
  12. python中字典的一些tips
  13. python 用生成器生成斐波那契数列
  14. python脚本转pyc踩了个坑。。。
  15. My collection of e-books and materials about Python
  16. Some tips of lambda in Python
  17. Some tips of dictionary in Python
  18. Using Python generator to generate Fibonacci sequence
  19. The conversion of Python script to PyC stepped on a pit...
  20. Python游戏开发,pygame模块,Python实现扫雷小游戏
  21. Python game development, pyGame module, python implementation of minesweeping games
  22. Python实用工具,email模块,Python实现邮件远程控制自己电脑
  23. Python utility, email module, python realizes mail remote control of its own computer
  24. 毫无头绪的自学Python,你可能连门槛都摸不到!【最佳学习路线】
  25. Python读取二进制文件代码方法解析
  26. Python字典的实现原理
  27. Without a clue, you may not even touch the threshold【 Best learning route]
  28. Parsing method of Python reading binary file code
  29. Implementation principle of Python dictionary
  30. You must know the function of pandas to parse JSON data - JSON_ normalize()
  31. Python实用案例,私人定制,Python自动化生成爱豆专属2021日历
  32. Python practical case, private customization, python automatic generation of Adu exclusive 2021 calendar
  33. 《Python实例》震惊了,用Python这么简单实现了聊天系统的脏话,广告检测
  34. "Python instance" was shocked and realized the dirty words and advertisement detection of the chat system in Python
  35. Convolutional neural network processing sequence for Python deep learning
  36. Python data structure and algorithm (1) -- enum type enum
  37. 超全大厂算法岗百问百答(推荐系统/机器学习/深度学习/C++/Spark/python)
  38. 【Python进阶】你真的明白NumPy中的ndarray吗?
  39. All questions and answers for algorithm posts of super large factories (recommended system / machine learning / deep learning / C + + / spark / Python)
  40. [advanced Python] do you really understand ndarray in numpy?
  41. 【Python进阶】Python进阶专栏栏主自述:不忘初心,砥砺前行
  42. [advanced Python] Python advanced column main readme: never forget the original intention and forge ahead
  43. python垃圾回收和缓存管理
  44. java调用Python程序
  45. java调用Python程序
  46. Python常用函数有哪些?Python基础入门课程
  47. Python garbage collection and cache management
  48. Java calling Python program
  49. Java calling Python program
  50. What functions are commonly used in Python? Introduction to Python Basics
  51. Python basic knowledge
  52. Anaconda5.2 安装 Python 库(MySQLdb)的方法
  53. Python实现对脑电数据情绪分析
  54. Anaconda 5.2 method of installing Python Library (mysqldb)
  55. Python implements emotion analysis of EEG data
  56. Master some advanced usage of Python in 30 seconds, which makes others envy it
  57. python爬取百度图片并对图片做一系列处理
  58. Python crawls Baidu pictures and does a series of processing on them
  59. python链接mysql数据库
  60. Python link MySQL database