欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

使用node搭建自动发图文微博机器人的方法

程序员文章站 2023-12-05 11:39:16
本文仅供学习交流,请勿用于商业用途,并遵守新浪微博相关规定。 代码目录 此微博机器人的实现功能如下: 模拟登陆新浪微博,获取cookie; 自动上传...

本文仅供学习交流,请勿用于商业用途,并遵守新浪微博相关规定。

代码目录

使用node搭建自动发图文微博机器人的方法

此微博机器人的实现功能如下:

  • 模拟登陆新浪微博,获取cookie;
  • 自动上传图片至微博图床;
  • 自动发送内容不同的图文微博;
  • 通过定时任务,实现周期性发微博任务。

效果图

使用node搭建自动发图文微博机器人的方法

图文内容我固定了,可自行使用第三方api获取要发送的内容或爬取第三方内容发送。(偷个懒...

使用node搭建自动发图文微博机器人的方法

要实现发送图文微博可以分为三个步骤

  • 登录微博。
  • 图片上传至微博图床获取pid。
  • 发送微博。

登录

登录可以使用puppeteer node库,很轻松的实现登录获取微博cookie,这里不多介绍,可以自行搜索puppeteer学习。

puppeteer是谷歌官方出品的一个通过devtools协议控制headless chrome的node库。可以通过puppeteer的提供的api直接控制chrome模拟大部分用户操作来进行ui test或者作为爬虫访问页面来收集数据。
async function login(username, password) {
  const browser = await puppeteer.launch({
    // headless: false,
    slowmo: 250,
    executablepath: ''
  });
  const page = (await browser.pages())[0];
  await page.setviewport({
    width: 1280,
    height: 800
  });

  await page.goto("https://weibo.com/");
  await page.waitfornavigation();
  await page.type("#loginname", username);
  await page.type("#pl_login_form > div > div:nth-child(3) > div.info_list.password > div > input", password);
  await page.click("#pl_login_form > div > div:nth-child(3) > div:nth-child(6)");
  await page.waitfornavigation().then(result => {
    return new promise((resolve) => {
      page.cookies().then(async cookie => {
        fs.createwritestream("cookie.txt").write(json.stringify(cookie), "utf8");//存储cookie
        await browser.close();//关闭打开的浏览器
        resolve(cookie);
      });
    })
  }).catch(e => {
    page.screenshot({
      path: 'code.png',
      type: 'png',
      x: 800,
      y: 200,
      width: 100,
      height: 100
    });
    return new promise((resolve, reject) => {
      readsyncbyrl("请输入验证码").then(async (code) => {
        await page.type("#pl_login_form > div > div:nth-child(3) > div.info_list.verify.clearfix > div > input", code);
        await page.click("#pl_login_form > div > div:nth-child(3) > div:nth-child(6)");
        await page.waitfornavigation();
        page.cookies().then(async cookie => {
          fs.createwritestream("cookie.txt").write(json.stringify(cookie), "utf8");
          await browser.close();
          resolve(cookie);
        });

      })
    })
  })
}

图片上传至微博图床

上传到微博图床可以看这里 http://weibo.com/minipublish 抓包看上传的接口过程,可以看到上传的是base64图片信息。所以上传前把图片转换成base64编码,而本地图片的编码和互联网链接图片的编码又不一样,这里使用的是互联网链接的图片,node本地图片转换成base64编码更简单些。上传成功后返回微博图床图片的pid。记住这个pid,发微博用的就是这个pid。

发送微博

有了微博cookie和图片pid后就可以发微博了,多张图片时pid之间以|隔开的。

async function weibopost(text, pic_ids = '', cookie) { //发送微博内容(支持带图片)
  return new promise(async (resolve, reject) => {
    if (cookie === '') {
      reject('error: cookie not set!');
    }
    let post_data = querystring.stringify({
      'location': 'v6_content_home',
      'text': text,
      'appkey': '',
      'style_type': '1',
      'pic_id': pic_ids,
      'tid': '',
      'pdetail': '',
      'mid': '',
      'isreedit': 'false',
      'rank': '0',
      'rankid': '',
      'module': 'stissue',
      'pub_source': 'main_',
      'pub_type': 'dialog',
      'ispri': '0',
      '_t': '0'
    });

    let post_options = {
      'accept': '*/*',
      'accept-encoding': 'gzip, deflate, br',
      'accept-language': 'zh-cn,zh;q=0.9,en;q=0.8,zh-tw;q=0.7',
      'connection': 'keep-alive',
      'content-length': buffer.bytelength(post_data),
      'content-type': 'application/x-www-form-urlencoded',
      'cookie': cookie,
      'host': 'weibo.com',
      'origin': 'https://weibo.com',
      'referer': 'https://weibo.com',
      'user-agent': 'mozilla/5.0 (macintosh; intel mac os x 10_13_3) applewebkit/537.36 (khtml, like gecko) chrome/64.0.3282.167 safari/537.36',
      'x-requested-with': 'xmlhttprequest'
    };


    let {
      data
    } = await axios.post('https://weibo.com/aj/mblog/add?ajwvr=6&__rnd=' + new date().gettime(), post_data, {
      withcredentials: true,
      headers: post_options
    })
    if (data.code == 100000) {
      console.log('\n' + text + '-----sent!' + '---' + new date().tolocalestring());
      resolve(data);
    } else {
      console.log('post error');
      reject('post error');
    }

  });
}

最后就是定时任务了,定时任务可以使用库,这里不多介绍,可以自行搜索学习。这里使用的是每隔10分钟发送一次。

function loginto() {
  login(config.username, config.password).then(async () => {
    let rule = null;
    rule = new schedule.recurrencerule();
    rule.minute = [01, 11, 21, 31, 41, 51];
    try {
      let cookie = await getcookie();
      getcontent(cookie);
    } catch (error) {
      console.log(error);
    }

    j = schedule.schedulejob(rule, async () => { //定时任务
      try {
        let cookie = await getcookie();
        getcontent(cookie);
      } catch (error) {
        console.log(error);
      }

    });
  })
}

代码地址:

参考

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。