经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » JS/JS库/框架 » Node.js » 查看文章
使用node搭建自动发图文微博机器人的方法
来源:jb51  时间:2019/3/22 12:08:51  对本文有异议

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

代码目录

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

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

效果图


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

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

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

登录

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

Puppeteer是谷歌官方出品的一个通过DevTools协议控制headless Chrome的Node库。可以通过Puppeteer的提供的api直接控制Chrome模拟大部分用户操作来进行UI Test或者作为爬虫访问页面来收集数据。
  1. async function login(username, password) {
  2. const browser = await puppeteer.launch({
  3. // headless: false,
  4. slowMo: 250,
  5. executablePath: ''
  6. });
  7. const page = (await browser.pages())[0];
  8. await page.setViewport({
  9. width: 1280,
  10. height: 800
  11. });
  12.  
  13. await page.goto("https://weibo.com/");
  14. await page.waitForNavigation();
  15. await page.type("#loginname", username);
  16. await page.type("#pl_login_form > div > div:nth-child(3) > div.info_list.password > div > input", password);
  17. await page.click("#pl_login_form > div > div:nth-child(3) > div:nth-child(6)");
  18. await page.waitForNavigation().then(result => {
  19. return new Promise((resolve) => {
  20. page.cookies().then(async cookie => {
  21. fs.createWriteStream("cookie.txt").write(JSON.stringify(cookie), "UTF8");//存储cookie
  22. await browser.close();//关闭打开的浏览器
  23. resolve(cookie);
  24. });
  25. })
  26. }).catch(e => {
  27. page.screenshot({
  28. path: 'code.png',
  29. type: 'png',
  30. x: 800,
  31. y: 200,
  32. width: 100,
  33. height: 100
  34. });
  35. return new Promise((resolve, reject) => {
  36. readSyncByRl("请输入验证码").then(async (code) => {
  37. await page.type("#pl_login_form > div > div:nth-child(3) > div.info_list.verify.clearfix > div > input", code);
  38. await page.click("#pl_login_form > div > div:nth-child(3) > div:nth-child(6)");
  39. await page.waitForNavigation();
  40. page.cookies().then(async cookie => {
  41. fs.createWriteStream("cookie.txt").write(JSON.stringify(cookie), "UTF8");
  42. await browser.close();
  43. resolve(cookie);
  44. });
  45.  
  46. })
  47. })
  48. })
  49. }

图片上传至微博图床

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

发送微博

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

  1. async function weibopost(text, pic_ids = '', cookie) { //发送微博内容(支持带图片)
  2. return new Promise(async (resolve, reject) => {
  3. if (cookie === '') {
  4. reject('Error: Cookie not set!');
  5. }
  6. let post_data = querystring.stringify({
  7. 'location': 'v6_content_home',
  8. 'text': text,
  9. 'appkey': '',
  10. 'style_type': '1',
  11. 'pic_id': pic_ids,
  12. 'tid': '',
  13. 'pdetail': '',
  14. 'mid': '',
  15. 'isReEdit': 'false',
  16. 'rank': '0',
  17. 'rankid': '',
  18. 'module': 'stissue',
  19. 'pub_source': 'main_',
  20. 'pub_type': 'dialog',
  21. 'isPri': '0',
  22. '_t': '0'
  23. });
  24.  
  25. let post_options = {
  26. 'Accept': '*/*',
  27. 'Accept-Encoding': 'gzip, deflate, br',
  28. 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,zh-TW;q=0.7',
  29. 'Connection': 'keep-alive',
  30. 'Content-Length': Buffer.byteLength(post_data),
  31. 'Content-Type': 'application/x-www-form-urlencoded',
  32. 'Cookie': cookie,
  33. 'Host': 'weibo.com',
  34. 'Origin': 'https://weibo.com',
  35. 'Referer': 'https://weibo.com',
  36. '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',
  37. 'X-Requested-With': 'XMLHttpRequest'
  38. };
  39.  
  40.  
  41. let {
  42. data
  43. } = await axios.post('https://weibo.com/aj/mblog/add?ajwvr=6&__rnd=' + new Date().getTime(), post_data, {
  44. withCredentials: true,
  45. headers: post_options
  46. })
  47. if (data.code == 100000) {
  48. console.log('\n' + text + '-----Sent!' + '---' + new Date().toLocaleString());
  49. resolve(data);
  50. } else {
  51. console.log('post error');
  52. reject('post error');
  53. }
  54.  
  55. });
  56. }

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

  1. function loginTo() {
  2. login(config.username, config.password).then(async () => {
  3. let rule = null;
  4. rule = new schedule.RecurrenceRule();
  5. rule.minute = [01, 11, 21, 31, 41, 51];
  6. try {
  7. let cookie = await getCookie();
  8. getContent(cookie);
  9. } catch (error) {
  10. console.log(error);
  11. }
  12.  
  13. j = schedule.scheduleJob(rule, async () => { //定时任务
  14. try {
  15. let cookie = await getCookie();
  16. getContent(cookie);
  17. } catch (error) {
  18. console.log(error);
  19. }
  20.  
  21. });
  22. })
  23. }

代码地址: github地址

参考

https://github.com/itibbers/weibo-post

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

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号