douyin-user-data-download

下载抖音用户主页数据!

当前为 2024-06-14 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name douyin-user-data-download
  3. // @namespace http://tampermonkey.net/
  4. // @version 0.4.1
  5. // @description 下载抖音用户主页数据!
  6. // @author xxmdmst
  7. // @match https://www.douyin.com/*
  8. // @icon https://xxmdmst.oss-cn-beijing.aliyuncs.com/imgs/favicon.ico
  9. // @grant GM_registerMenuCommand
  10. // @grant GM_setValue
  11. // @grant GM_getValue
  12. // @require https://cdnjs.cloudflare.com/ajax/libs/jszip/3.6.0/jszip.min.js
  13. // @license MIT
  14. // ==/UserScript==
  15.  
  16. (function () {
  17. const startPipeline = (start) => {
  18. if (confirm(start ? "是否开启本地下载通道?\n开户后会向本地服务发送数据" : "是否关闭本地下载通道?")) {
  19. GM_setValue("localDownload", start);
  20. window.location.reload();
  21. }
  22. }
  23. let localDownload = GM_getValue("localDownload");
  24. if (localDownload) {
  25. GM_registerMenuCommand("✅关闭上报本地通道", () => {
  26. startPipeline(false);
  27. })
  28. } else {
  29. GM_registerMenuCommand("⛔️开启上报本地通道", () => {
  30. startPipeline(true);
  31. })
  32. }
  33. let localDownloadUrl = GM_getValue("localDownloadUrl");
  34. GM_registerMenuCommand("♐设置本地上报地址", () => {
  35. localDownloadUrl = GM_getValue("localDownloadUrl");
  36. if (!localDownloadUrl) localDownloadUrl = 'http://localhost:8080/data';
  37. let newlocalDownloadUrl = prompt("请输入新的上报地址:", localDownloadUrl);
  38. if (!newlocalDownloadUrl) {
  39. alert("取消设置或设置了空白!");
  40. } else {
  41. GM_setValue("localDownloadUrl", newlocalDownloadUrl);
  42. alert("当前上报地址已经修改为:" + newlocalDownloadUrl);
  43. localDownloadUrl = newlocalDownloadUrl;
  44. }
  45. });
  46. let table;
  47.  
  48. function initGbkTable() {
  49. // https://en.wikipedia.org/wiki/GBK_(character_encoding)#Encoding
  50. const ranges = [
  51. [0xA1, 0xA9, 0xA1, 0xFE],
  52. [0xB0, 0xF7, 0xA1, 0xFE],
  53. [0x81, 0xA0, 0x40, 0xFE],
  54. [0xAA, 0xFE, 0x40, 0xA0],
  55. [0xA8, 0xA9, 0x40, 0xA0],
  56. [0xAA, 0xAF, 0xA1, 0xFE],
  57. [0xF8, 0xFE, 0xA1, 0xFE],
  58. [0xA1, 0xA7, 0x40, 0xA0],
  59. ];
  60. const codes = new Uint16Array(23940);
  61. let i = 0;
  62.  
  63. for (const [b1Begin, b1End, b2Begin, b2End] of ranges) {
  64. for (let b2 = b2Begin; b2 <= b2End; b2++) {
  65. if (b2 !== 0x7F) {
  66. for (let b1 = b1Begin; b1 <= b1End; b1++) {
  67. codes[i++] = b2 << 8 | b1
  68. }
  69. }
  70. }
  71. }
  72. table = new Uint16Array(65536);
  73. table.fill(0xFFFF);
  74. const str = new TextDecoder('gbk').decode(codes);
  75. for (let i = 0; i < str.length; i++) {
  76. table[str.charCodeAt(i)] = codes[i]
  77. }
  78. }
  79.  
  80. function str2gbk(str, opt = {}) {
  81. if (!table) {
  82. initGbkTable()
  83. }
  84. const NodeJsBufAlloc = typeof Buffer === 'function' && Buffer.allocUnsafe;
  85. const defaultOnAlloc = NodeJsBufAlloc
  86. ? (len) => NodeJsBufAlloc(len)
  87. : (len) => new Uint8Array(len);
  88. const defaultOnError = () => 63;
  89. const onAlloc = opt.onAlloc || defaultOnAlloc;
  90. const onError = opt.onError || defaultOnError;
  91.  
  92. const buf = onAlloc(str.length * 2);
  93. let n = 0;
  94.  
  95. for (let i = 0; i < str.length; i++) {
  96. const code = str.charCodeAt(i);
  97. if (code < 0x80) {
  98. buf[n++] = code;
  99. continue
  100. }
  101. const gbk = table[code];
  102.  
  103. if (gbk !== 0xFFFF) {
  104. buf[n++] = gbk;
  105. buf[n++] = gbk >> 8
  106. } else if (code === 8364) {
  107. buf[n++] = 0x80
  108. } else {
  109. const ret = onError(i, str);
  110. if (ret === -1) {
  111. break
  112. }
  113. if (ret > 0xFF) {
  114. buf[n++] = ret;
  115. buf[n++] = ret >> 8
  116. } else {
  117. buf[n++] = ret
  118. }
  119. }
  120. }
  121. return buf.subarray(0, n)
  122. }
  123.  
  124. function formatSeconds(seconds) {
  125. const timeUnits = ['小时', '分', '秒'];
  126. const timeValues = [
  127. Math.floor(seconds / 3600),
  128. Math.floor((seconds % 3600) / 60),
  129. seconds % 60
  130. ];
  131. return timeValues.map((value, index) => value > 0 ? value + timeUnits[index] : '').join('');
  132. }
  133.  
  134. const timeFormat = (timestamp = null, fmt = 'yyyy-mm-dd') => {
  135. // 其他更多是格式化有如下:
  136. // yyyy:mm:dd|yyyy:mm|yyyy年mm月dd日|yyyy年mm月dd日 hh时MM分等,可自定义组合
  137. timestamp = parseInt(timestamp);
  138. // 如果为null,则格式化当前时间
  139. if (!timestamp) timestamp = Number(new Date());
  140. // 判断用户输入的时间戳是秒还是毫秒,一般前端js获取的时间戳是毫秒(13位),后端传过来的为秒(10位)
  141. if (timestamp.toString().length === 10) timestamp *= 1000;
  142. let date = new Date(timestamp);
  143. let ret;
  144. let opt = {
  145. "y{4,}": date.getFullYear().toString(), // 年
  146. "y+": date.getFullYear().toString().slice(2,), // 年
  147. "m+": (date.getMonth() + 1).toString(), // 月
  148. "d+": date.getDate().toString(), // 日
  149. "h+": date.getHours().toString(), // 时
  150. "M+": date.getMinutes().toString(), // 分
  151. "s+": date.getSeconds().toString() // 秒
  152. // 有其他格式化字符需求可以继续添加,必须转化成字符串
  153. };
  154. for (let k in opt) {
  155. ret = new RegExp("(" + k + ")").exec(fmt);
  156. if (ret) {
  157. fmt = fmt.replace(ret[1], (ret[1].length === 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
  158. }
  159. }
  160. return fmt
  161. };
  162. let aweme_list = [];
  163. let userKey = [
  164. "昵称", "关注", "粉丝", "获赞",
  165. "抖音号", "IP属地", "性别",
  166. "位置", "签名", "作品数", "主页"
  167. ];
  168. let userData = [];
  169. let createEachButtonTimer;
  170.  
  171. function copyText(text, node) {
  172. let oldText = node.textContent;
  173. navigator.clipboard.writeText(text).then(r => {
  174. node.textContent = "复制成功";
  175. }).catch((e) => {
  176. node.textContent = "复制失败";
  177. })
  178. setTimeout(() => node.textContent = oldText, 2000);
  179. }
  180.  
  181. function copyUserData(node) {
  182. if (userData.length === 0) {
  183. alert("没有捕获到用户数据!");
  184. return;
  185. }
  186. let text = [];
  187. for (let i = 0; i < userKey.length; i++) {
  188. let key = userKey[i];
  189. let value = userData[userData.length - 1][i];
  190. if (value) text.push(key + ":" + value.toString().trim());
  191. }
  192. copyText(text.join("\n"), node);
  193. }
  194.  
  195. function createVideoButton(text, top, func) {
  196. const button = document.createElement("button");
  197. button.textContent = text;
  198. button.style.position = "absolute";
  199. button.style.right = "0px";
  200. button.style.top = top;
  201. button.style.opacity = "0.5";
  202. if (func) {
  203. button.addEventListener("click", (event) => {
  204. event.preventDefault();
  205. event.stopPropagation();
  206. func();
  207. });
  208. }
  209. return button;
  210. }
  211.  
  212. function createDownloadLink(blob, filename, ext, prefix = "") {
  213. if (filename === null) {
  214. filename = userData.length > 0 ? userData[userData.length - 1][0] : document.title;
  215. }
  216. const url = URL.createObjectURL(blob);
  217. const link = document.createElement('a');
  218. link.href = url;
  219. link.download = prefix + filename.replace(/[\/:*?"<>|\s]/g, "").slice(0, 40) + "." + ext;
  220. link.click();
  221. URL.revokeObjectURL(url);
  222. }
  223.  
  224. function txt2file(txt, filename, ext) {
  225. createDownloadLink(new Blob([txt], {type: 'text/plain'}), filename, ext);
  226. }
  227.  
  228. function getAwemeName(aweme) {
  229. let name = aweme.item_title ? aweme.item_title : aweme.caption;
  230. if (!name) name = aweme.desc ? aweme.desc : aweme.awemeId;
  231. return `【${aweme.date.slice(0, 10)}】` + name.replace(/[\/:*?"<>|\s]+/g, "").slice(0, 27).replace(/\.\d+$/g, "");
  232. }
  233.  
  234. function createEachButton() {
  235. let targetNodes = document.querySelectorAll("div[data-e2e='user-post-list'] > ul[data-e2e='scroll-list'] > li a");
  236. for (let i = 0; i < targetNodes.length; i++) {
  237. let targetNode = targetNodes[i];
  238. if (targetNode.dataset.added) {
  239. continue;
  240. }
  241. let aweme = aweme_list[i];
  242. let copyDescButton = createVideoButton("复制描述", "0px");
  243. copyDescButton.addEventListener("click", (event) => {
  244. event.preventDefault();
  245. event.stopPropagation();
  246. copyText(aweme.desc, copyDescButton);
  247. })
  248. targetNode.appendChild(copyDescButton);
  249. targetNode.appendChild(createVideoButton("打开视频源", "20px", () => window.open(aweme.url)));
  250. let downloadVideoButton = createVideoButton("下载视频", "40px", () => {
  251. let xhr = new XMLHttpRequest();
  252. xhr.open('GET', aweme.url.replace("http://", "https://"), true);
  253. xhr.responseType = 'blob';
  254. xhr.onload = (e) => {
  255. createDownloadLink(xhr.response, getAwemeName(aweme), (aweme.images ? "mp3" : "mp4"));
  256. };
  257. xhr.onprogress = (event) => {
  258. if (event.lengthComputable) {
  259. downloadVideoButton.textContent = "下载" + (event.loaded * 100 / event.total).toFixed(1) + '%';
  260. }
  261. };
  262. xhr.send();
  263. });
  264. targetNode.appendChild(downloadVideoButton);
  265. if (aweme.images) {
  266. targetNode.appendChild(createVideoButton("图片打包下载", "60px", () => {
  267. const zip = new JSZip();
  268. // console.log(aweme.images);
  269. downloadVideoButton.textContent = "图片下载并打包中...";
  270. const promises = aweme.images.map((link, index) => {
  271. return fetch(link)
  272. .then((response) => response.arrayBuffer())
  273. .then((buffer) => {
  274. downloadVideoButton.textContent = `图片已下载【${index + 1}/${aweme.images.length}】`;
  275. zip.file(`image_${index + 1}.jpg`, buffer);
  276. });
  277. });
  278. Promise.all(promises)
  279. .then(() => {
  280. return zip.generateAsync({type: "blob"});
  281. })
  282. .then((content) => {
  283. createDownloadLink(content, getAwemeName(aweme), "zip", "【图文】");
  284. downloadVideoButton.textContent = "图文打包完成";
  285. });
  286. }));
  287. }
  288. targetNode.dataset.added = "true";
  289. }
  290. }
  291.  
  292. function flush() {
  293. if (createEachButtonTimer !== undefined) {
  294. clearTimeout(createEachButtonTimer);
  295. createEachButtonTimer = undefined;
  296. }
  297. createEachButtonTimer = setTimeout(createEachButton, 500);
  298. data_button.p2.textContent = `${aweme_list.length}`;
  299. let img_num = aweme_list.filter(a => a.images).length;
  300. img_button.p2.textContent = `${img_num}`;
  301. msg_pre.textContent = `已加载${aweme_list.length}个作品,${img_num}个图文\n激活上方头像可展开下载按钮`;
  302. }
  303.  
  304. let flag = false;
  305.  
  306. function formatJsonData(json_data) {
  307. return json_data.aweme_list.map(item => Object.assign(
  308. {
  309. "awemeId": item.aweme_id,
  310. "item_title": item.item_title,
  311. "caption": item.caption,
  312. "desc": item.desc,
  313. "tag": item.text_extra.map(tag => tag.hashtag_name).filter(tag => tag).join("#"),
  314. "video_tag": item.video_tag.map(tag => tag.tag_name).filter(tag => tag).join("->")
  315. },
  316. {
  317. "diggCount": item.statistics.digg_count,
  318. "commentCount": item.statistics.comment_count,
  319. "collectCount": item.statistics.collect_count,
  320. "shareCount": item.statistics.share_count
  321. },
  322. {
  323. "date": timeFormat(item.create_time, "yyyy-mm-dd hh:MM:ss"),
  324. "duration": formatSeconds(Math.round(item.video.duration / 1000)),
  325. "url": item.video.play_addr.url_list[0],
  326. "cover": item.video.cover.url_list[0],
  327. "images": item.images ? item.images.map(row => row.url_list.pop()) : null,
  328. "uid": item.author.uid,
  329. "nickname": item.author.nickname
  330. }
  331. ));
  332. }
  333.  
  334. function sendLocalData(jsonData) {
  335. if (!localDownload) return;
  336. fetch(localDownloadUrl, {
  337. method: 'POST',
  338. headers: {
  339. 'Content-Type': 'application/json'
  340. },
  341. body: JSON.stringify(jsonData)
  342. })
  343. .then(response => response.json())
  344. .then(responseData => {
  345. console.log('成功:', responseData);
  346. })
  347. .catch(error => {
  348. console.log('上报失败,请检查本地程序是否已经启动!');
  349. });
  350. }
  351.  
  352. function interceptResponse() {
  353. const originalSend = XMLHttpRequest.prototype.send;
  354. XMLHttpRequest.prototype.send = function () {
  355. const self = this;
  356. this.onreadystatechange = function () {
  357. if (self.readyState === 4 && self._url) {
  358. if (self._url.indexOf("/aweme/v1/web/aweme/post") > -1) {
  359. let jsonData = formatJsonData(JSON.parse(self.response));
  360. aweme_list.push(...jsonData);
  361. if (domLoadedTimer === null) {
  362. flush();
  363. } else {
  364. flag = true;
  365. }
  366. sendLocalData(jsonData);
  367. } else if (self._url.indexOf("/aweme/v1/web/user/profile/other") > -1) {
  368. let userInfo = JSON.parse(self.response).user;
  369. for (let key in userInfo) {
  370. if (!userInfo[key]) userInfo[key] = "";
  371. }
  372. if (userInfo.district) userInfo.city += "·" + userInfo.district;
  373. userInfo.unique_id = '\t' + (userInfo.unique_id ? userInfo.unique_id : userInfo.short_id);
  374. userData.push([
  375. userInfo.nickname, userInfo.following_count, userInfo.mplatform_followers_count,
  376. userInfo.total_favorited, userInfo.unique_id, userInfo.ip_location.replace("IP属地:", ""),
  377. userInfo.gender === 2 ? "女" : "男",
  378. userInfo.city, '"' + userInfo.signature + '"', userInfo.aweme_count, "https://www.douyin.com/user/" + userInfo.sec_uid
  379. ]);
  380. }
  381. }
  382. };
  383. originalSend.apply(this, arguments);
  384. };
  385. }
  386.  
  387.  
  388. function downloadData(node, encoding) {
  389. if (node.disabled) {
  390. alert("下载正在处理中,请不要重复点击按钮!");
  391. return;
  392. }
  393. node.disabled = true;
  394. try {
  395. // if (userData.length > 0) {
  396. // text += userKey.join(",") + "\n";
  397. // text += userData.map(row => row.join(",")).join("\n") + "\n\n";
  398. // }
  399. let text = "作品描述,作品链接,点赞数,评论数,收藏数,分享数,发布时间,时长,标签,分类,封面,下载链接\n";
  400. aweme_list.forEach(aweme => {
  401. text += ['"' + aweme.desc.replace(/,/g, ',').replace(/"/g, '""') + '"',
  402. "https://www.douyin.com/video/" + aweme.awemeId,
  403. aweme.diggCount, aweme.commentCount,
  404. aweme.collectCount, aweme.shareCount, aweme.date,
  405. aweme.duration, aweme.tag, aweme.video_tag,
  406. aweme.cover, aweme.url].join(",") + "\n"
  407. });
  408. if (encoding === "gbk") {
  409. text = str2gbk(text);
  410. }
  411. txt2file(text, null, "csv");
  412. } finally {
  413. node.disabled = false;
  414. }
  415. }
  416.  
  417. let img_button, data_button, msg_pre;
  418.  
  419. function createMsgBox() {
  420. msg_pre = document.createElement('pre');
  421. msg_pre.textContent = '等待上方头像加载完毕';
  422. msg_pre.style.color = 'white';
  423. msg_pre.style.position = 'fixed';
  424. msg_pre.style.right = '5px';
  425. msg_pre.style.top = '60px';
  426. msg_pre.style.color = 'white';
  427. msg_pre.style.zIndex = '90000';
  428. msg_pre.style.opacity = "0.5";
  429. document.body.appendChild(msg_pre);
  430. }
  431.  
  432. function scrollPageToBottom(scroll_button) {
  433. let scrollInterval;
  434.  
  435. function scrollLoop() {
  436. let endText = document.querySelector("div[data-e2e='user-post-list'] > ul[data-e2e='scroll-list'] + div div").innerText;
  437. if (endText || (userData.length > 0 && aweme_list.length > userData[userData.length - 1][9] - 5)) {
  438. clearInterval(scrollInterval);
  439. scrollInterval = null;
  440. scroll_button.p1.textContent = "已加载全部!";
  441. } else {
  442. scrollTo(0, document.body.scrollHeight);
  443. }
  444. }
  445.  
  446. scroll_button.addEventListener('click', () => {
  447. if (!scrollInterval) {
  448. scrollInterval = setInterval(scrollLoop, 1200);
  449. scroll_button.p1.textContent = "停止自动下拉";
  450. } else {
  451. clearInterval(scrollInterval);
  452. scrollInterval = null;
  453. scroll_button.p1.textContent = "开启自动下拉";
  454. }
  455. });
  456. }
  457.  
  458. function createAllButton() {
  459. let dom = document.querySelector("#douyin-header-menuCt pace-island > div > div:nth-last-child(1) ul a:nth-last-child(1)");
  460. let baseNode = dom.cloneNode(true);
  461. baseNode.removeAttribute("target");
  462. baseNode.removeAttribute("rel");
  463. baseNode.removeAttribute("href");
  464. let svgChild = baseNode.querySelector("svg");
  465. if (svgChild) baseNode.removeChild(svgChild);
  466.  
  467. function createNewButton(name, num = "0") {
  468. let button = baseNode.cloneNode(true);
  469. button.p1 = button.querySelector("p:nth-child(1)");
  470. button.p2 = button.querySelector("p:nth-child(2)");
  471. button.p1.textContent = name;
  472. button.p2.textContent = num;
  473. dom.after(button);
  474. return button;
  475. }
  476.  
  477. function createCommonElement(tagName, attrs = {}, text = "") {
  478. const tag = document.createElement(tagName);
  479. for (const [k, v] of Object.entries(attrs)) {
  480. tag.setAttribute(k, v);
  481. }
  482. if (text) tag.textContent = text;
  483. tag.addEventListener('click', (event) => event.stopPropagation());
  484. return tag;
  485. }
  486.  
  487. img_button = createNewButton("图文打包下载");
  488. img_button.addEventListener('click', () => downloadImg(img_button));
  489.  
  490. let downloadCoverButton = createNewButton("封面打包下载", "");
  491. downloadCoverButton.addEventListener('click', () => downloadCover(downloadCoverButton));
  492.  
  493. data_button = createNewButton("下载已加载的数据");
  494. data_button.p1.after(createCommonElement("label", {'for': 'gbk'}, 'gbk'));
  495. let checkbox = createCommonElement("input", {'type': 'checkbox', 'id': 'gbk'});
  496. checkbox.checked = localStorage.getItem("gbk") === "1";
  497. checkbox.onclick = (event) => {
  498. event.stopPropagation();
  499. localStorage.setItem("gbk", checkbox.checked ? "1" : "0");
  500. };
  501. data_button.p1.after(checkbox);
  502. data_button.addEventListener('click', () => downloadData(data_button, checkbox.checked ? "gbk" : "utf-8"));
  503.  
  504. scrollPageToBottom(createNewButton("开启自动下拉到底", ""));
  505.  
  506. let share_button = document.querySelector("#frame-user-info-share-button");
  507. let node = share_button.cloneNode(true);
  508. node.span = node.querySelector("span");
  509. node.span.innerHTML = "复制作者信息";
  510. node.addEventListener('click', () => copyUserData(node.span));
  511. share_button.after(node);
  512. }
  513.  
  514. async function downloadCover(node) {
  515. if (node.disabled) {
  516. alert("下载正在处理中,请不要重复点击按钮!");
  517. return;
  518. }
  519. node.disabled = true;
  520. try {
  521. const zip = new JSZip();
  522. msg_pre.textContent = `下载封面并打包中...`;
  523. let promises = aweme_list.map((aweme, index) => {
  524. let awemeName = getAwemeName(aweme) + ".jpg";
  525. return fetch(aweme.cover)
  526. .then(response => response.arrayBuffer())
  527. .then(buffer => zip.file(awemeName, buffer))
  528. .then(() => msg_pre.textContent = `${index + 1}/${aweme_list.length} ` + awemeName)
  529. });
  530. Promise.all(promises).then(() => {
  531. return zip.generateAsync({type: "blob"})
  532. }).then((content) => {
  533. createDownloadLink(content, null, "zip", "【封面】");
  534. msg_pre.textContent = "封面打包完成";
  535. node.disabled = false;
  536. })
  537. } finally {
  538. node.disabled = false;
  539. }
  540. }
  541.  
  542. async function downloadImg(node) {
  543. if (node.disabled) {
  544. alert("下载正在处理中,请不要重复点击按钮!");
  545. return;
  546. }
  547. node.disabled = true;
  548. try {
  549. const zip = new JSZip();
  550. let flag = true;
  551. let aweme_img_list = aweme_list.filter(a => a.images);
  552. for (let [i, aweme] of aweme_img_list.entries()) {
  553. let awemeName = getAwemeName(aweme);
  554. msg_pre.textContent = `${i + 1}/${aweme_img_list.length} ` + awemeName;
  555. let folder = zip.folder(awemeName);
  556. await Promise.all(aweme.images.map((link, index) => {
  557. return fetch(link)
  558. .then((res) => res.arrayBuffer())
  559. .then((buffer) => {
  560. folder.file(`image_${index + 1}.jpg`, buffer);
  561. });
  562. }));
  563. flag = false;
  564. }
  565. if (flag) {
  566. alert("当前页面未发现图文链接");
  567. node.disabled = false;
  568. return;
  569. }
  570. msg_pre.textContent = "图文打包中...";
  571. zip.generateAsync({type: "blob"})
  572. .then((content) => {
  573. createDownloadLink(content, null, "zip", "【图文】");
  574. msg_pre.textContent = "图文打包完成";
  575. node.disabled = false;
  576. });
  577. } finally {
  578. node.disabled = false;
  579. }
  580.  
  581. }
  582.  
  583. function douyinVideoDownloader() {
  584. function run() {
  585. let downloadOption = [{name: '打开视频源', id: 'toLink'}];
  586. let videoElements = document.querySelectorAll('video');
  587. if (videoElements.length === 0) return;
  588. //把自动播放的video标签选择出来
  589. let playVideoElements = [];
  590. videoElements.forEach(function (element) {
  591. let autoplay = element.getAttribute('autoplay');
  592. if (autoplay !== null) {
  593. playVideoElements.push(element);
  594. }
  595. })
  596. let videoContainer = location.href.indexOf('modal_id') !== -1
  597. ? playVideoElements[0]
  598. : playVideoElements[playVideoElements.length - 1];
  599. if (!videoContainer) return;
  600. //获取视频播放地址
  601. let url = videoContainer && videoContainer.children.length > 0 && videoContainer.children[0].src
  602. ? videoContainer.children[0].src
  603. : videoContainer.src;
  604. //获取视频ID,配合自定义id使用
  605. let videoId;
  606. let resp = url.match(/^(https:)?\/\/.+\.com\/([a-zA-Z0-9]+)\/[a-zA-Z0-9]+\/video/);
  607. let res = url.match(/blob:https:\/\/www.douyin.com\/(.*)/);
  608. if (resp && resp[2]) {
  609. videoId = resp[2];
  610. } else if (res && res[1]) {
  611. videoId = res[1]
  612. } else {
  613. videoId = videoContainer.getAttribute('data-xgplayerid')
  614. }
  615. let playContainer = videoContainer.parentNode.parentNode.querySelector('.xg-right-grid');
  616. if (!playContainer) return;
  617. //在对主页就行视频浏览时会出现多个按钮,删除不需要的,只保留当前对应的
  618. let videoDownloadDom = playContainer.querySelector('#scriptVideoDownload' + videoId);
  619. if (videoDownloadDom) {
  620. let dom = playContainer.querySelectorAll('.xgplayer-playclarity-setting');
  621. dom.forEach(function (d) {
  622. let btn = d.querySelector('.btn');
  623. if (d.id !== 'scriptVideoDownload' + videoId && btn.innerText === '下载') {
  624. d.parentNode.removeChild(d);
  625. }
  626. });
  627. return;
  628. }
  629. if (videoContainer && playContainer) {
  630. let playClarityDom = playContainer.querySelector('.xgplayer-playclarity-setting');
  631. if (!playClarityDom) return;
  632.  
  633. let palyClarityBtn = playClarityDom.querySelector('.btn');
  634. if (!palyClarityBtn) return;
  635.  
  636. let downloadDom = playClarityDom.cloneNode(true);
  637. downloadDom.setAttribute('id', 'scriptVideoDownload' + videoId);
  638.  
  639. if (location.href.indexOf('search') === -1) {
  640. downloadDom.style = 'margin-top:-68px;padding-top:100px;padding-left:20px;padding-right:20px;';
  641. } else {
  642. downloadDom.style = 'margin-top:0px;padding-top:100px;';
  643. }
  644.  
  645. let downloadText = downloadDom.querySelector('.btn');
  646. downloadText.innerText = '下载';
  647. downloadText.style = 'font-size:14px;font-weight:600;';
  648. downloadText.setAttribute('id', 'zhmDouyinDownload' + videoId);
  649. let detail = playContainer.querySelector('xg-icon:nth-of-type(1)').children[0];
  650. let linkUrl = detail.getAttribute('href') ? detail.getAttribute('href') : location.href;
  651.  
  652. if (linkUrl.indexOf('www.douyin.com') === -1) {
  653. linkUrl = '//www.douyin.com' + linkUrl;
  654. }
  655.  
  656. downloadText.setAttribute('data-url', linkUrl);
  657. downloadText.removeAttribute('target');
  658. downloadText.setAttribute('href', 'javascript:void(0);');
  659.  
  660. let virtualDom = downloadDom.querySelector('.virtual');
  661. downloadDom.onmouseover = function () {
  662. if (location.href.indexOf('search') === -1) {
  663. virtualDom.style = 'display:block !important';
  664. } else {
  665. virtualDom.style = 'display:block !important;margin-bottom:37px;';
  666. }
  667. }
  668.  
  669. downloadDom.onmouseout = function () {
  670. virtualDom.style = 'display:none !important';
  671. }
  672.  
  673. let downloadHtml = '';
  674. downloadOption.forEach(function (item) {
  675. if (item.id === "toLink") {
  676. downloadHtml += `<div style="text-align:center;" class="item ${item.id}" id="${item.id}${videoId}">${item.name}</div>`;
  677. }
  678. })
  679. if (downloadDom.querySelector('.virtual')) {
  680. downloadDom.querySelector('.virtual').innerHTML = downloadHtml;
  681. }
  682. playClarityDom.after(downloadDom);
  683. //直接打开
  684. let toLinkDom = playContainer.querySelector('#toLink' + videoId);
  685. if (toLinkDom) {
  686. toLinkDom.addEventListener('click', function () {
  687. if (url.match(/^blob/)) {
  688. alert("加密视频地址,无法直接打开");
  689. } else {
  690. window.open(url);
  691. }
  692. })
  693. }
  694. }
  695. }
  696.  
  697. setInterval(run, 500);
  698. }
  699.  
  700. if (document.title === "验证码中间页") {
  701. return
  702. }
  703. createMsgBox();
  704. interceptResponse();
  705. douyinVideoDownloader();
  706. let domLoadedTimer;
  707. const checkElementLoaded = () => {
  708. const element = document.querySelector('#douyin-header-menuCt pace-island > div > div:nth-last-child(1) ul a');
  709. if (element) {
  710. console.log('顶部栏加载完毕');
  711. msg_pre.textContent = "头像加载完成\n若需要下载用户数据,需进入目标用户主页";
  712. clearInterval(domLoadedTimer);
  713. domLoadedTimer = null;
  714. createAllButton();
  715. // scrollPageToBottom();
  716. if (flag) flush();
  717. }
  718. };
  719. window.onload = () => {
  720. domLoadedTimer = setInterval(checkElementLoaded, 700);
  721. }
  722. })();

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址