[pig框架实战] 手撕视频管理发布平台[08] - 自动化发布视频到微信视频号上

自动化发布视频到视频号上

前端代码实现

在上一节,我们已经写好了发布按钮的界面,现在只需要编写处理函数FabuShipinhao即可,具体逻辑如下所示。

注意事项

  • 请求的超时时间长一些,保证视频发布完成,这里设置了两分钟timeout: 2 * 60 * 1000
  • 参数检测,前端能拿到视频的各种属性,可以先校验一下,减少不必要的服务器请求
    图例一

    FabuShipinhao(row) {
      console.log(row);
      // 参数检测
      if (row.myFlagShipinhao) {
        this.$notify.warning("视频已经发布过了");
        return
      }
      if (row.myTitleCn.length == 0) {
        this.$notify.warning("视频标题不能为空");
        return
      }
      if (row.myTagsCn.length == 0) {
        this.$notify.warning("视频标签不能为空");
        return
      }
      
      return request({
        url: '/myvideos/myvideos/FabuShipinhao',
        method: 'post',
        params: {jId: row.jid},
        timeout: 2 * 60 * 1000
      })
      .then((data) => {
        console.log(data)
        if (data.data.data) {
          this.$notify.success("修改成功");
          // 重新获取视频数据的各种属性
          this.getDataList();
        } else {
          this.$notify.warning("失败了");
        }
      })
      .catch(() => {
        this.$notify.warn("异常");
      });
    },

后台代码实现

参数加密使用的是hutool的工具函数

  • json生成 String j = JSONUtil.toJsonStr(sortedMap);
  • json中Unicode字符处理j = UnicodeUtil.toUnicode(j);
  • base64加密 String encode = Base64.encode(j);

然后拼接命令行String cmd = StrUtil.format("{} {} {}", path_python, path_script, encode);
最后调用命令行Runtime.getRuntime().exec(cmd);


	@Override
	public boolean FabuShipinhao(String jId, String myTitleCn, String myTagsCn) {
		SortedMap<String, String> sortedMap = new TreeMap<String, String>();
		sortedMap.put("jId", jId);
		sortedMap.put("myTitleCn", myTitleCn);
		sortedMap.put("myTagsCn", myTagsCn);
		String j = JSONUtil.toJsonStr(sortedMap);
		j = UnicodeUtil.toUnicode(j);
		System.out.println(j);

		// Base64
		String encode = Base64.encode(j);
		System.out.println(encode);

		// 执行任务
		boolean ret = false;
		String cmd = StrUtil.format("{} {} {}", path_python, path_script, encode);
		Process pro = null;
		try {
			pro = Runtime.getRuntime().exec(cmd);
			int exitVal = 0;
			if( pro.waitFor(2 * 60, TimeUnit.SECONDS) ) {
				exitVal = pro.exitValue();
				System.out.println(exitVal);

				ret = (exitVal == 0);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		return ret;
	}

自动化实现(python+selenium)

关于自动化环境的搭建,可以参考文章 [selenium][01] - 环境搭建

参数解析(服务器调用加密过程反过来,将参数解析出来即可)

  • base64解密 base64.b64decode(param_b64)
  • json解析 json.loads

class VideoParam:
    """
    从java后台传过来的视频参数
        param_j         {"jId": "7021124933367385346", "myTitleCn": "小慧君超强cos 是天使喔~~~", "myTagsCn": "#cosplay #小姐姐 #小慧君"}
                        {"jId": "7021124933367385346", "myTitleCn": "\u5c0f\u6167\u541b\u8d85\u5f3acos \u662f\u5929\u4f7f\u5594~~~", "myTagsCn": "#cosplay #\u5c0f\u59d0\u59d0 #\u5c0f\u6167\u541b"}
        param_b64       eyJqSWQiOiAiNzAyMTEyNDkzMzM2NzM4NTM0NiIsICJteVRpdGxlQ24iOiAiXHU1YzBmXHU2MTY3XHU1NDFiXHU4ZDg1XHU1ZjNhY29zIFx1NjYyZlx1NTkyOVx1NGY3Zlx1NTU5NH5+fiIsICJteVRhZ3NDbiI6ICIjY29zcGxheSAjXHU1YzBmXHU1OWQwXHU1OWQwICNcdTVjMGZcdTYxNjdcdTU0MWIifQ==
    """
    def __init__(self, param_b64):
        # base64解密
        param_j = json.loads(base64.b64decode(param_b64))
        print(param_j)

        # 解析参数
        self.param = types.SimpleNamespace(**param_j)

        self.path_root = r'J:/_ALL/CODE/gitee/constellations/pig-ui/public/_tiktok_res/'

自动化

  • 指定chrome的用户数据目录options.add_argument(r'--user-data-dir=xxx')
  • 判断视频是否上传完成driver.find_element_by_tag_name('video')
  • 判断是否发布完成driver.current_url,大多数视频得调整封面,所以这里不自动点击发表按钮
def publish_shipinhao(param):
    '''
    作用:发布微信视频号
    '''
    import selenium
    from selenium import webdriver
    from selenium.webdriver.common.keys import Keys

    #     time.sleep(10)
    options = webdriver.ChromeOptions()
    options.binary_location = r'C:\Program Files\Google\Chrome\Application\chrome.exe'
    options.add_argument(r'--user-data-dir=G:\\_ALL\\chrome--user-data-dir\\公众号\\浏览器登录\\20000-爬虫分析')
    # didable "Chrome is being controled by an automated test software"
    options.add_argument('disable-infobars')
    driver = webdriver.Chrome(executable_path=r'J:\_ALL\CODE\venv\py386_automate\Scripts\chromedriver.exe', options=options)

    # 进入微信视频号创作者页面,并上传视频
    driver.get("https://channels.weixin.qq.com/post/create")
    time.sleep(2)
    driver.find_element_by_xpath('//input[@type="file"]').send_keys(param.get_path_video())

    # 等待视频上传完成
    # 检查一:等待video标签出现
    while True:
        time.sleep(3)
        try:
            video = driver.find_element_by_tag_name('video')
            if video:
                break
        except Exception as e:
            print("视频还在上传中···")

    print("视频已上传完成!")

    # 输入视频描述
    driver.find_element_by_xpath('//*[@data-placeholder="添加描述"]').send_keys(param.get_title())

    # 添加位置
    driver.find_element_by_xpath('//*[@class="position-display-wrap"]').click()
    time.sleep(2)
    driver.find_element_by_xpath('//*[text()="不显示位置"]').click()

    # 人工进行检查并发布
    while True:
        if driver.current_url == 'https://channels.weixin.qq.com/platform/post/list':
            print('发布完成')
            break

        print('等待发布...')
        time.sleep(3)
    # # 点击发布
    # driver.find_element_by_xpath('//*[text()="发表"]').click()

    return 0

参考资料

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

夜猫逐梦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值