最近在查看一个API的数据,效果很好,但是里面只有一部分我想要的内容
如果是简单一点的可以直接获取
如下比如我想要提取返回的代码中关键的字符串:"video": "这里的内容"
// 定义一个正则表达式来匹配 '"video": "链接"' 格式的字符串 var regex = /"video":s*"([^"]+)"/gi; // 用于存储所有找到的链接 var links = []; // 执行正则表达式搜索 var match; while ((match = regex.exec(document.body.textContent)) !== null) { // match[1] 包含链接 links.push(match[1]); } // 打印所有找到的链接,每个链接一行 links.forEach(function(link, index) { console.log('video' + (index + 1) + ': ' + link); });
但是如果返回的结果有10万行代码左右阁下该如何应对?
我突发奇想,让浏览器自己滚动,一边滚动一边扫描就像PLC一样,一边扫描一边执行程序
// 定义一个正则表达式来匹配 '"video": "链接"' 格式的字符串 var regex = /"video":s*"([^"]+)"/g; var matches = []; var interval; var step = 100; // 每次滚动的像素数 var position = 0; // 当前滚动位置 // 滚动函数 function scrollToBottom() { position += step; window.scrollTo(0, position); // 检查是否到达页面底部 if (position >= document.body.scrollHeight) { clearInterval(interval); printMatches(); } else { // 继续寻找匹配项 findMatches(); } } // 查找匹配项的函数 function findMatches() { var text = document.body.innerText; var match; while ((match = regex.exec(text)) !== null) { matches.push(match[1]); // 只添加链接部分 } } // 打印匹配结果的函数 function printMatches() { console.log('找到的链接数量:', matches.length); matches.forEach(function(link, index) { console.log('video' + (index + 1) + ': ' + link); }); } // 开始滚动和查找匹配项 interval = setInterval(scrollToBottom, 50); // 每50毫秒滚动一次
讲解:首先定义了一个滚动函数
scrollToBottom
,它会逐步向下滚动页面,并在每次滚动后调用findMatches
函数来查找匹配的链接。当滚动到页面底部时,通过clearInterval
停止滚动,并调用printMatches
函数来打印所有找到的链接。