[新手上路]批处理新手入门导读[视频教程]批处理基础视频教程[视频教程]VBS基础视频教程[批处理精品]批处理版照片整理器
[批处理精品]纯批处理备份&还原驱动[批处理精品]CMD命令50条不能说的秘密[在线下载]第三方命令行工具[在线帮助]VBScript / JScript 在线参考
返回列表 发帖
本帖最后由 flashercs 于 2018-11-26 18:53 编辑

楼主是win7吗?powershell 是2.0 版本?
下载第一个网站的
保存为zgshige.bat
  1. 0<1/*,:
  2. @echo off
  3. %windir%\system32\CScript.exe -nologo -e:jscript %0
  4. pause
  5. exit /b
  6. */;
  7. (function () {
  8.     var xhr = (function () {
  9.         var aXMLHttpVers = ['MSXML2.XMLHTTP.6.0', 'MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP', 'Microsoft.XMLHTTP'];
  10.         for (var i = 0; i < aXMLHttpVers.length; i++) {
  11.             try {
  12.                 return new ActiveXObject(aXMLHttpVers[i]);
  13.             } catch (error) { }
  14.         }
  15.         showError('Can\'t build XMLHTTP automation object.');
  16.         WScript.Quit(1);
  17.     })(),
  18.         fso = new ActiveXObject('Scripting.FileSystemObject'),
  19.         htmldoc = new ActiveXObject('htmlfile'),
  20.         oADO = new ActiveXObject('ADODB.Stream'),
  21.         domain = "http://www.zgshige.com",
  22.         outFile = "shige.txt",
  23.         cacheFile = "cache.txt",
  24.         tsOut,
  25.         tsCache,
  26.         oCache = {},
  27.         url,
  28.         aIndex = [],
  29.         nextPage,
  30.         nodes,
  31.         reScriptNode = /<script[^>]*>[\s\S]*?<\/script>(?!['"'])/g,
  32.         i,
  33.         l;
  34.     oADO.Mode = 3;
  35.     new ActiveXObject('WScript.Shell').CurrentDirectory = fso.GetParentFolderName(WScript.ScriptFullName);
  36.     try {
  37.         tsCache = fso.OpenTextFile(cacheFile, 1, true);
  38.     } catch (e) {
  39.         WScript.Echo('can not read cache file ' + cacheFile);
  40.         WScript.Quit(1);
  41.     }
  42.     while (!tsCache.AtEndOfStream) {
  43.         oCache[tsCache.ReadLine()] = true;
  44.     }
  45.     tsCache.Close();
  46.     try {
  47.         tsCache = fso.OpenTextFile(cacheFile, 8, true);
  48.     } catch (e) {
  49.         showError(e, 'can not write cache file ' + cacheFile);
  50.         WScript.Quit(2);
  51.     }
  52.     try {
  53.         tsOut = fso.OpenTextFile(outFile, 8, true, -1);//unicode encoding
  54.     } catch (e) {
  55.         showError(e, 'can not write file ' + outFile);
  56.         WScript.Quit(3);
  57.     }
  58.     // url可以自己设置起始下载位置;例如 url = 'http://www.zgshige.com/zcms/catalog/15112/pc/index_29937.shtml';
  59.     url = 'http://www.zgshige.com/sg/index.shtml';
  60.     while (url) {
  61.         if (!getHTML(url)) break;
  62.         aIndex.length = 0;
  63.         nodes = htmldoc.documentElement.getElementsByClassName('fc-green text-uppercase');
  64.         for (i = 0, l = nodes.length; i < l; ++i) {
  65.             aIndex.push(parseURL(nodes[i].getAttribute('href'), url));
  66.         }
  67.         nodes = htmldoc.documentElement.getElementsByClassName('fc_ch1');
  68.         for (nextPage = null, i = 0, l = nodes.length; i < l; ++i) {
  69.             if (nodes[i].firstChild.nodeValue === '下一页') {
  70.                 nextPage = parseURL(nodes[i].parentNode.getAttribute('href'), url);
  71.                 break;
  72.             }
  73.         }
  74.         // WScript.StdOut.WriteLine('aIndex.length=' + aIndex.length);
  75.         // WScript.StdOut.WriteLine('innerHTML=' + htmldoc.documentElement.childNodes[0].innerHTML);
  76.         for (i = 0, l = aIndex.length; i < l; ++i) {
  77.             url = aIndex[i];
  78.             if (oCache[url] || !getHTML(url)) continue;
  79.             try {
  80.                 tsOut.WriteLine(('TTT' + htmldoc.documentElement.getElementsByTagName('h3')[0].innerText + '\r\n' + htmldoc.documentElement.getElementsByClassName('m-lg font14')[0].innerText).replace(/\r?\n */g, '<br/>\r\n'));
  81.                 tsCache.WriteLine(url);
  82.             } catch (e) {
  83.             }
  84.         }
  85.         url = nextPage;
  86.     }
  87.     tsOut.close();
  88.     tsCache.close();
  89.     WScript.Quit();
  90.     function parseURL(href, url) {
  91.         var $path = href.replace(/^[^:]*:/, '');
  92.         if (/^\/\/.*/.test($path)) {
  93.             return href;
  94.         } else if (/^\/.*/.test($path)) {
  95.             return domain + $path;
  96.         } else {
  97.             return url.replace(/[^\/]+$/, '') + $path;
  98.         }
  99.     }
  100.     function showError(err, source) {
  101.         WScript.StdOut.WriteLine('[object Error]' === Object.prototype.toString.call(err) ?
  102.             [
  103.                 err.name,
  104.                 'source: ' + (undefined === source ? '' : source),
  105.                 'number: ' + (err.number >>> 0).toString(16),
  106.                 'Information: ' + err.message
  107.             ].join('\r\n')
  108.             :
  109.             err);
  110.     }
  111.     function getHTML(url) {
  112.         WScript.StdOut.Write('fetching ' + url + '...')
  113.         xhr.open('GET', url, false);
  114.         xhr.setRequestHeader('Accept', 'text/html, application/xhtml+xml, application/xml; q=0.9, */*; q=0.8');
  115.         xhr.setRequestHeader('Accept-Language', 'en-US, en; q=0.8, zh-Hans-CN; q=0.5, zh-Hans; q=0.3');
  116.         xhr.setRequestHeader('Accept-Encoding', 'gzip, deflate');
  117.         xhr.setRequestHeader('TE', 'gzip, deflate');
  118.         xhr.setRequestHeader('Cache-Control', 'no-cache');
  119.         xhr.setRequestHeader('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/17.17134');
  120.         try {
  121.             xhr.send();
  122.             if (200 === xhr.status) {
  123.                 oADO.Type = 1;
  124.                 oADO.Open();
  125.                 oADO.Write(xhr.responseBody);
  126.                 oADO.Position = 0;
  127.                 oADO.Type = 2;
  128.                 oADO.Charset = 'utf-8';
  129.                 htmldoc.open();
  130.                 htmldoc.write(oADO.ReadText(-1).replace(reScriptNode, ''));
  131.             } else {
  132.                 WScript.StdOut.WriteLine('failed')
  133.                 return false
  134.             }
  135.         } catch (e) {
  136.             WScript.StdOut.WriteLine('failed')
  137.             return false;
  138.         } finally {
  139.             htmldoc.close();
  140.             oADO.Close();
  141.         }
  142.         WScript.StdOut.WriteLine('success')
  143.         return true;
  144.     }
  145. })();
复制代码
1

评分人数

    • lxh623: 真诚感谢!技术 + 1

TOP

52shici还有两个内容 works 和 posts 开始搞错了都......也不知要哪个?都弄上吧.
52shiciWorks.bat
  1. 0<1/*,:
  2. @echo off
  3. CScript.exe -nologo -e:jscript %0
  4. pause
  5. exit /b
  6. */;
  7. (function () {
  8.     var xhr = (function () {
  9.         var aXMLHttpVers = ['MSXML2.XMLHTTP.6.0', 'MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP', 'Microsoft.XMLHTTP'];
  10.         for (var i = 0; i < aXMLHttpVers.length; i++) {
  11.             try {
  12.                 return new ActiveXObject(aXMLHttpVers[i]);
  13.             } catch (error) { }
  14.         }
  15.         showError('Can\'t build XMLHTTP automation object.');
  16.         WScript.Quit(1);
  17.     })(),
  18.         fso = new ActiveXObject('Scripting.FileSystemObject'),
  19.         htmldoc = new ActiveXObject('htmlfile'),
  20.         domain = "http://www.52shici.com",
  21.         outFile = "52shici_works.txt",
  22.         cacheFile = "cache_52shici_works.txt",
  23.         tsOut,
  24.         tsCache,
  25.         oCache = {},
  26.         url,
  27.         reCrLfS = /\r?\n */g,
  28.         i,
  29.         l,
  30.         aIndex = [];
  31.     new ActiveXObject('WScript.Shell').CurrentDirectory = fso.GetParentFolderName(WScript.ScriptFullName);
  32.     try {
  33.         tsCache = fso.OpenTextFile(cacheFile, 1, true);
  34.     } catch (e) {
  35.         showError('can not read cache file ' + cacheFile);
  36.         WScript.Quit(1);
  37.     }
  38.     while (!tsCache.AtEndOfStream) {
  39.         oCache[tsCache.ReadLine()] = true;
  40.     }
  41.     tsCache.Close();
  42.     try {
  43.         tsCache = fso.OpenTextFile(cacheFile, 8, true);
  44.     } catch (e) {
  45.         showError(e, 'can not write cache file ' + cacheFile);
  46.         WScript.Quit(2);
  47.     }
  48.     try {
  49.         tsOut = fso.OpenTextFile(outFile, 8, true, -1);//unicode encoding
  50.     } catch (e) {
  51.         showError(e, 'can not write file ' + outFile);
  52.         WScript.Quit(3);
  53.     }
  54.     // main
  55.     for (var type = 0; type <= 19; ++type) {
  56.         var url = 'http://www.52shici.com/original.php?type=' + type + '&page=';
  57.         var totalPages;
  58.         if (!getHTMLindex(url + 1, true)) continue;
  59.         var body = htmldoc.body;
  60.         totalPgs = body.lastChild.innerText.match(/当前\d+\/(\d+)页/)[1];
  61.         WSH.Echo('totalpages=' + totalPgs);
  62.         for (var m = 1; m <= totalPgs; ++m) {
  63.             if (oCache[url + m] || !getHTMLindex(url + m)) continue;
  64.             body = htmldoc.body;
  65.             var aList = body.getElementsByTagName('a');
  66.             aIndex.length = 0;
  67.             for (i = 0, l = aList.length; i < l; ++i) {
  68.                 aIndex.push(parseURL(aList[i].getAttribute('href'), url));
  69.             }
  70.             for (i = 0, l = aIndex.length; i < l; ++i) {
  71.                 getContent(aIndex[i]);
  72.             }
  73.             tsCache.WriteLine(url + m);
  74.         }
  75.     }
  76.     tsOut.close();
  77.     tsCache.close();
  78.     WScript.Quit();
  79.     function getContent(url) {
  80.         if (oCache[url] || !getHTML(url)) return;
  81.         var main = htmldoc.body.children[0];
  82.         var nodes = main.children;
  83.         try {
  84.             for (var i = 0, l = nodes.length; i < l; ++i) {
  85.                 var item = nodes[i];
  86.                 switch (item.className) {
  87.                     case 'works-h1':
  88.                         var title = 'TTT ' + item.children[0].innerText;
  89.                         // WSH.Echo( 'title: '+title);
  90.                         var author = item.children[1].innerText.replace('文/', '作者:');
  91.                         // WSH.Echo( 'author: '+author);
  92.                         break;
  93.                     case 'works-content':
  94.                         var content = item.innerText;
  95.                         i = l;
  96.                         break;
  97.                     default:
  98.                         break;
  99.                 }
  100.             }
  101.             tsOut.WriteLine((title + '\r\n' + author + '\r\n' + content).replace(reCrLfS, '<br/>\r\n'));
  102.             tsCache.WriteLine(url);
  103.         } catch (e) {
  104.             showError(e);
  105.         }
  106.     }
  107.     function showError(err, source) {
  108.         WScript.StdOut.WriteLine('[object Error]' === Object.prototype.toString.call(err) ?
  109.             [
  110.                 err.name,
  111.                 'source: ' + (undefined === source ? '' : source),
  112.                 'number: ' + (err.number >>> 0).toString(16),
  113.                 'Information: ' + err.message
  114.             ].join('\r\n')
  115.             :
  116.             err);
  117.     }
  118.     function getHTMLindex(url, boltotalPages) {
  119.         WScript.StdOut.Write('fetching ' + url + '...')
  120.         xhr.open('GET', url, false);
  121.         xhr.setRequestHeader('Accept', 'text/html, application/xhtml+xml, application/xml; q=0.9, */*; q=0.8');
  122.         xhr.setRequestHeader('Accept-Language', 'en-US, en; q=0.8, zh-Hans-CN; q=0.5, zh-Hans; q=0.3');
  123.         xhr.setRequestHeader('host', 'www.52shici.com/');
  124.         xhr.setRequestHeader('Connection', 'close');
  125.         xhr.setRequestHeader('Cache-Control', 'no-cache');
  126.         xhr.setRequestHeader('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/17.17134');
  127.         try {
  128.             xhr.send();
  129.             // WSH.Echo(xhr.responseText.match(/<span[^>]*class=['"]mt['"][^>]*>[^<]*<\/span>/i)[0]);
  130.             // WSH.Quit();
  131.             if (200 === xhr.status) {
  132.                 htmldoc.open();
  133.                 htmldoc.write('<!DOCTYPE html><html><head></head><body>' + xhr.responseText.match(/<ul[^>]*id="listWorks"[^>]*>[\s\S]*?<\/ul>/i)[0] + (boltotalPages ? xhr.responseText.match(/<span[^>]*class=['"]mt['"][^>]*>[^<]*<\/span>/i)[0] : '') + '</body></html>');
  134.             } else {
  135.                 WScript.StdOut.WriteLine('failed. status:' + xhr.status);
  136.                 return false
  137.             }
  138.         } catch (e) {
  139.             WScript.StdOut.WriteLine('failed');
  140.             return false;
  141.         } finally {
  142.             htmldoc.close();
  143.         }
  144.         WScript.StdOut.WriteLine('success');
  145.         return true;
  146.     }
  147.     function getHTML(url) {
  148.         WScript.StdOut.Write('fetching ' + url + '...')
  149.         xhr.open('GET', url, false);
  150.         xhr.setRequestHeader('Accept', 'text/html, application/xhtml+xml, application/xml; q=0.9, */*; q=0.8');
  151.         xhr.setRequestHeader('Accept-Language', 'en-US, en; q=0.8, zh-Hans-CN; q=0.5, zh-Hans; q=0.3');
  152.         xhr.setRequestHeader('host', 'www.52shici.com/');
  153.         xhr.setRequestHeader('Connection', 'close');
  154.         xhr.setRequestHeader('Cache-Control', 'no-cache');
  155.         xhr.setRequestHeader('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/17.17134');
  156.         try {
  157.             xhr.send();
  158.             if (200 === xhr.status) {
  159.                 htmldoc.open();
  160.                 var aTxt = xhr.responseText.match(/<div class="main"[\s\S]+(?=<!--main end -->)/i);
  161.                 htmldoc.write('<!DOCTYPE html><html><head></head><body>' + aTxt[0] + '</body></html>');
  162.             } else {
  163.                 WScript.StdOut.WriteLine('failed. status:' + xhr.status);
  164.                 return false
  165.             }
  166.         } catch (e) {
  167.             WScript.StdOut.WriteLine('failed');
  168.             return false;
  169.         } finally {
  170.             htmldoc.close();
  171.         }
  172.         WScript.StdOut.WriteLine('success');
  173.         return true;
  174.     }
  175.     function parseURL(href, url) {
  176.         var $path = href.replace(/^[^:]*:/, '');
  177.         if (/^\/\/.*/.test($path)) {
  178.             return href;
  179.         } else if (/^\/.*/.test($path)) {
  180.             return domain + $path;
  181.         } else {
  182.             return url.replace(/[^\/]+$/, '') + $path;
  183.         }
  184.     }
  185. })();
复制代码
52shiciPosts.bat
  1. 0<1/*,:
  2. @echo off
  3. CScript.exe -nologo -e:jscript %0
  4. pause
  5. exit /b
  6. */;
  7. (function () {
  8.     var xhr = (function () {
  9.         var aXMLHttpVers = ['MSXML2.XMLHTTP.6.0', 'MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP', 'Microsoft.XMLHTTP'];
  10.         for (var i = 0; i < aXMLHttpVers.length; i++) {
  11.             try {
  12.                 return new ActiveXObject(aXMLHttpVers[i]);
  13.             } catch (error) { }
  14.         }
  15.         showError('Can\'t build XMLHTTP automation object.');
  16.         WScript.Quit(1);
  17.     })(),
  18.         fso = new ActiveXObject('Scripting.FileSystemObject'),
  19.         htmldoc = new ActiveXObject('htmlfile'),
  20.         domain = "http://www.52shici.com",
  21.         outFile = "52shici_posts.txt",
  22.         cacheFile = "cache_52shici_posts.txt",
  23.         tsOut,
  24.         tsCache,
  25.         oCache = {},
  26.         url,
  27.         reCrLfS = /\r?\n */g,
  28.         i,
  29.         l = 300000,
  30.         strOut,
  31.         nodeContent,
  32.         sTitle,
  33.         sAuthor,
  34.         sContent;
  35.     new ActiveXObject('WScript.Shell').CurrentDirectory = fso.GetParentFolderName(WScript.ScriptFullName);
  36.     try {
  37.         tsCache = fso.OpenTextFile(cacheFile, 1, true);
  38.     } catch (e) {
  39.         showError('can not read cache file ' + cacheFile);
  40.         WScript.Quit(1);
  41.     }
  42.     while (!tsCache.AtEndOfStream) {
  43.         oCache[tsCache.ReadLine()] = true;
  44.     }
  45.     tsCache.Close();
  46.     try {
  47.         tsCache = fso.OpenTextFile(cacheFile, 8, true);
  48.     } catch (e) {
  49.         showError(e, 'can not write cache file ' + cacheFile);
  50.         WScript.Quit(2);
  51.     }
  52.     try {
  53.         tsOut = fso.OpenTextFile(outFile, 8, true, -1);//unicode encoding
  54.     } catch (e) {
  55.         showError(e, 'can not write file ' + outFile);
  56.         WScript.Quit(3);
  57.     }
  58.     // main
  59.     for (i = 1; i < l; ++i) {
  60.         if (oCache['' + i]) continue;
  61.         url = 'http://www.52shici.com/posts.php?id=' + i;
  62.         if (!getHTML(url)) continue;
  63.         var node = htmldoc.documentElement.childNodes[1].childNodes[0];
  64.         try {
  65.             for (var m = 0, n = node.childNodes.length; m < n; ++m) {
  66.                 var item = node.childNodes[m];
  67.                 switch (item.className) {
  68.                     case 'posts-h1':
  69.                         sTitle = 'TTT ' + item.innerText;
  70.                         break;
  71.                     case 'posts-h2':
  72.                         sAuthor = '作者:' + item.firstChild.innerText;
  73.                         break;
  74.                     case 'posts-content':
  75.                         item.removeChild(item.lastChild);
  76.                         sContent = item.innerText;
  77.                         break;
  78.                     default:
  79.                         break;
  80.                 }
  81.             }
  82.             strOut = sTitle + '\r\n' + sAuthor + '\r\n' + sContent;
  83.             tsOut.WriteLine(strOut.replace(reCrLfS, '<br/>\r\n'));
  84.             tsCache.WriteLine(i);
  85.         } catch (e) {
  86.             continue;
  87.         }
  88.     }
  89.     tsOut.close();
  90.     tsCache.close();
  91.     WScript.Quit();
  92.     function showError(err, source) {
  93.         WScript.StdOut.WriteLine('[object Error]' === Object.prototype.toString.call(err) ?
  94.             [
  95.                 err.name,
  96.                 'source: ' + (undefined === source ? '' : source),
  97.                 'number: ' + (err.number >>> 0).toString(16),
  98.                 'Information: ' + err.message
  99.             ].join('\r\n')
  100.             :
  101.             err);
  102.     }
  103.     function getHTML(url) {
  104.         WScript.StdOut.Write('fetching ' + url + '...')
  105.         xhr.open('GET', url, false);
  106.         xhr.setRequestHeader('Accept', 'text/html, application/xhtml+xml, application/xml; q=0.9, */*; q=0.8');
  107.         xhr.setRequestHeader('Accept-Language', 'en-US, en; q=0.8, zh-Hans-CN; q=0.5, zh-Hans; q=0.3');
  108.         xhr.setRequestHeader('host', 'www.52shici.com/');
  109.         xhr.setRequestHeader('Connection', 'close');
  110.         xhr.setRequestHeader('Cache-Control', 'no-cache');
  111.         xhr.setRequestHeader('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/17.17134');
  112.         try {
  113.             xhr.send();
  114.             if (200 === xhr.status) {
  115.                 htmldoc.open();
  116.                 var aTxt = xhr.responseText.match(/<div class="sidebar"[\s\S]+(?=<div class="posts-do")/i);
  117.                 if (!aTxt) throw false;
  118.                 htmldoc.write('<!DOCTYPE html><html><head><meta http-equiv="Content-Type" content="text/html; charset=GB2312" /></head><body>' + aTxt[0] + '</div></body></html>');
  119.             } else {
  120.                 WScript.StdOut.WriteLine('failed. status:' + xhr.status);
  121.                 return false
  122.             }
  123.         } catch (e) {
  124.             WScript.StdOut.WriteLine('failed');
  125.             return false;
  126.         } finally {
  127.             htmldoc.close();
  128.         }
  129.         WScript.StdOut.WriteLine('success');
  130.         return true;
  131.     }
  132. })();
复制代码
1

评分人数

TOP

本帖最后由 flashercs 于 2018-12-6 22:27 编辑

先设置52shici.html的根目录路径;
保存 提取52shici_Works.bat
  1. @echo off
  2. REM 设置htmlRoot = 52shici的html文件根目录
  3. set "htmlRoot=E:\PowerShell\WebHttpRequest\52shici\html"
  4. REM 设置txtFilePath = 提取的文本文件名,放在脚本同目录下
  5. set "txtFilePath=提取52shici.txt"
  6. for /f "tokens=1 delims=:" %%A in ('findstr /n "#######*" %0') do more +%%A %0 >"%~dpn0.ps1"
  7. powershell.exe -ExecutionPolicy Bypass -File "%~dpn0.ps1" "%htmlRoot%" "%~dp0%txtFilePath%"
  8. pause
  9. exit /b
  10. ################################################################
  11. param([string]$htmlRoot, [string]$txtFilePath)
  12. $sw = [System.IO.StreamWriter]::new($txtFilePath, $true, [System.Text.Encoding]::Unicode)
  13. $sw.AutoFlush = $true
  14. # [string]$scriptPath = [System.IO.Path]::GetDirectoryName($MyInvocation.MyCommand.Defination)
  15. $htmldoc = New-Object -ComObject htmlfile
  16. $null = $htmldoc.IHTMLDocument2_open()
  17. $htmldoc.IHTMLDocument2_write('<!DOCTYPE html><html><head><meta charset="utf-8" /><meta http-equiv="X-UA-Compatible" content="IE=edge"><title>Page Title</title><meta name="viewport" content="width=device-width, initial-scale=1"></head><body></body></html>')
  18. $htmldoc.IHTMLDocument2_close()
  19. [System.IO.Directory]::GetFiles($htmlRoot, '*.html', [System.IO.SearchOption]::AllDirectories)|ForEach-Object {
  20.     $m = [System.IO.File]::ReadAllText($_, [System.Text.Encoding]::UTF8) -match '<div class="main"[\s\S]+(?=<!--main end -->)'
  21.     if ($m) {
  22.         Write-Host "提取$_" -ForegroundColor Green
  23.         try {
  24.             $htmldoc.body.innerHTML = $Matches[0]
  25.             $div = $htmldoc.body.firstChild
  26.             $nodeh1 = $div.getElementsByClassName('works-h1')[0]
  27.             $title = 'TTT ' + $nodeh1.children[0].innerText
  28.             $author = $nodeh1.children[1].innerText
  29.             $content = $div.getElementsByClassName('works-content')[0].innerText
  30.             $sw.WriteLine((($title + "`r`n" + $author + "`r`n" + $content + "`r`n") -replace "`r?`n\s*", "<br/>`r`n"))
  31.         }
  32.         catch {
  33.                
  34.         }
  35.     }
  36. }
  37. Remove-Variable -Name htmldoc
  38. $sw.Close()
复制代码

TOP

本帖最后由 flashercs 于 2018-12-6 22:28 编辑

提取zgshige.bat
  1. @echo off
  2. REM 设置htmlRoot = zgshige的html文件根目录
  3. set "htmlRoot=E:\PowerShell\WebHttpRequest\zgshige\htmlsrc"
  4. REM 设置txtFilePath = 提取的文本文件名
  5. set "txtFilePath=提取zgshige.txt"
  6. for /f "tokens=1 delims=:" %%A in ('findstr /n "#######*" %0') do more +%%A %0 >"%~dpn0.ps1"
  7. powershell.exe -ExecutionPolicy Bypass -File "%~dpn0.ps1" "%htmlRoot%" "%~dp0%txtFilePath%"
  8. pause
  9. exit /b
  10. ################################################################
  11. param([string]$htmlRoot, [string]$txtFilePath)
  12. $sw = [System.IO.StreamWriter]::new($txtFilePath, $true, [System.Text.Encoding]::Unicode)
  13. $sw.AutoFlush = $true
  14. # [string]$scriptPath = [System.IO.Path]::GetDirectoryName($MyInvocation.MyCommand.Defination)
  15. $htmldoc = New-Object -ComObject htmlfile
  16. $null = $htmldoc.IHTMLDocument2_open()
  17. $htmldoc.IHTMLDocument2_write('<!DOCTYPE html><html><head><meta charset="utf-8" /><meta http-equiv="X-UA-Compatible" content="IE=edge"><title>Page Title</title><meta name="viewport" content="width=device-width, initial-scale=1"></head><body></body></html>')
  18. $htmldoc.IHTMLDocument2_close()
  19. [System.IO.Directory]::GetFiles($htmlRoot, '*.html', [System.IO.SearchOption]::AllDirectories)|ForEach-Object {
  20.     $m = [System.IO.File]::ReadAllText($_, [System.Text.Encoding]::UTF8) -match '(?<=<!-- 诗歌正文开始 -->)[\s\S]+(?=<!-- 诗歌正文结束 -->)'
  21.     if ($m) {
  22.         Write-Host "提取$_" -ForegroundColor Green
  23.         try {
  24.             $htmldoc.body.innerHTML = $Matches[0]
  25.             $title = 'TTT ' + $htmldoc.body.getElementsByTagName('h3')[0].innerText
  26.             $author = $htmldoc.body.children[1].children[0].children[0].innerText
  27.             $content = $htmldoc.body.getElementsByClassName('m-lg font14')[0].innerText
  28.             $sw.WriteLine((($title + "`r`n" + $author + "`r`n" + $content + "`r`n") -replace "\r?\n\s*", "<br/>`r`n"))
  29.         }
  30.         catch {
  31.                
  32.         }
  33.     }
  34. }
  35. Remove-Variable -Name htmldoc
  36. $sw.Close()
复制代码

TOP

回复 19# lxh623


    请不要删除或改名 文件名含有cache的.txt 文件 ,那么下次运行就是忽略已下载过的了.

TOP

回复 21# lxh623


    后面的导航页下载很慢,但是内容页下载很快, 5楼更新了一下代码, 59行可以自定义起始下载的导航页面,有 范例

TOP

回复 24# lxh623

已修改了

TOP

本帖最后由 flashercs 于 2018-12-4 07:50 编辑

回复 27# lxh623

有作者了 需要重新下载的.
zgshige.bat
  1. 0<1/*,:
  2. @echo off
  3. CScript.exe -nologo -e:jscript %0
  4. pause
  5. exit /b
  6. */;
  7. function makeXHR() {
  8.     for (var i = 0; i < aXMLHttpVers.length; i++) {
  9.         try {
  10.             return new ActiveXObject(aXMLHttpVers[i]);
  11.         } catch (error) { }
  12.     }
  13.     showError('Can\'t build XMLHTTP automation object.');
  14.     WScript.Quit(1);
  15. }
  16. function makeHtmldoc() {
  17.     var htmldoc = new ActiveXObject('htmlfile');
  18.     htmldoc.open();
  19.     htmldoc.write('<!DOCTYPE html><html><head><meta charset="utf-8" /><meta http-equiv="X-UA-Compatible" content="IE=edge"><title>Page Title</title><meta name="viewport" content="width=device-width, initial-scale=1"></head><body></body></html>');
  20.     htmldoc.close();
  21.     return htmldoc;
  22. }
  23. function makeADOStream() {
  24.     var oADO = new ActiveXObject('ADODB.Stream');
  25.     oADO.Mode = 3;
  26.     return oADO;
  27. }
  28. function byte2str(ado, byteArr, sEncoding) {
  29.     ado.Type = 1;
  30.     ado.Open();
  31.     ado.Write(byteArr);
  32.     ado.Position = 0;
  33.     ado.Type = 2;
  34.     ado.Charset = sEncoding;
  35.     var s = ado.ReadText(-1);
  36.     ado.Close();
  37.     return s;
  38. }
  39. function xhrWorkers() {
  40.     var url;
  41.     var xhr_ = makeXHR();
  42.     var htmldoc = makeHtmldoc();
  43.     var oADO = makeADOStream();
  44.     var re = /<!-- 诗歌正文开始 -->[\s\S]+(?=<!-- 诗歌正文结束 -->)/i;
  45.     xhr_.onReadyStateChange = function () {
  46.         if (xhr_.readyState === 4) {
  47.             if (xhr_.status === 200) {
  48.                 var str = byte2str(oADO, xhr_.responseBody, 'utf-8');
  49.                 var m = str.match(re);
  50.                 if (m) {
  51.                     try {
  52.                         htmldoc.body.innerHTML = m[0];
  53.                         var title = 'TTT ' + htmldoc.body.getElementsByTagName('h3')[0].innerText;
  54.                         var author = htmldoc.body.children[1].children[0].children[0].innerText;
  55.                         var content = htmldoc.body.getElementsByClassName('m-lg font14')[0].innerText;
  56.                         tsOut.WriteLine((title + '\r\n' + author + '\r\n' + content + '\r\n').replace(/\r?\n\s*/g, '<br/>\r\n'));
  57.                         tsCache.WriteLine(url);
  58.                         WScript.StdOut.WriteLine(url);
  59.                     } catch (e) {
  60.                         // WScript.StdOut.WriteLine(htmldoc.documentElement.getElementsByClassName ? 'className' : htmldoc.documentElement.getElementsByTagName ? 'tagName' : 'nothing');
  61.                     }
  62.                 }
  63.             } else {
  64.                 WScript.StdOut.WriteLine(url + ' status=' + xhr_.status);
  65.             }
  66.             aXhr.push(worker);
  67.         }
  68.     };
  69.     var worker = {
  70.         job: function (method, uri, async) {
  71.             url = uri;
  72.             xhr_.open(method, uri, async);
  73.             // setRequestHeaders(xhr_);
  74.             xhr_.send();
  75.         }
  76.     };
  77.     return worker;
  78. }
  79. function setRequestHeaders(xhr_) {
  80.     xhr_.setRequestHeader('Accept', 'text/html, application/xhtml+xml, application/xml; q=0.9, */*; q=0.8');
  81.     xhr_.setRequestHeader('Accept-Language', 'en-US, en; q=0.8, zh-Hans-CN; q=0.5, zh-Hans; q=0.3');
  82.     xhr_.setRequestHeader('Accept-Encoding', 'gzip, deflate');
  83.     xhr_.setRequestHeader('TE', 'gzip, deflate');
  84.     // xhr_.setRequestHeader('Connection', 'close');
  85.     xhr_.setRequestHeader('Cache-Control', 'no-cache');
  86.     xhr_.setRequestHeader('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/17.17134');
  87. }
  88. function parseURL(href, url) {
  89.     var $path = href.replace(/^[^:]*:/, '');
  90.     if (/^\/\/.*/.test($path)) {
  91.         return href;
  92.     } else if (/^\/.*/.test($path)) {
  93.         return domain + $path;
  94.     } else {
  95.         return url.replace(/[^\/]+$/, '') + $path;
  96.     }
  97. }
  98. function showError(err, source) {
  99.     WScript.StdOut.WriteLine('[object Error]' === Object.prototype.toString.call(err) ?
  100.         [
  101.             err.name,
  102.             'source: ' + (undefined === source ? '' : source),
  103.             'number: ' + (err.number >>> 0).toString(16),
  104.             'Information: ' + err.message
  105.         ].join('\r\n')
  106.         :
  107.         err);
  108. }
  109. var aXMLHttpVers = ['MSXML2.XMLHTTP.6.0', 'MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP', 'Microsoft.XMLHTTP'],
  110.     fso = new ActiveXObject('Scripting.FileSystemObject'),
  111.     domain = "http://www.zgshige.com",
  112.     outFile = "zgshige.txt",
  113.     cacheFile = "cache_zgshige.txt",
  114.     tsOut,
  115.     tsCache,
  116.     oCache = {};
  117. new ActiveXObject('WScript.Shell').CurrentDirectory = fso.GetParentFolderName(WScript.ScriptFullName);
  118. try {
  119.     tsCache = fso.OpenTextFile(cacheFile, 1, true);
  120. } catch (e) {
  121.     WScript.Echo('can not read cache file ' + cacheFile);
  122.     WScript.Quit(1);
  123. }
  124. while (!tsCache.AtEndOfStream) {
  125.     oCache[tsCache.ReadLine()] = true;
  126. }
  127. tsCache.Close();
  128. try {
  129.     tsCache = fso.OpenTextFile(cacheFile, 8, true);
  130. } catch (e) {
  131.     showError(e, 'can not write cache file ' + cacheFile);
  132.     WScript.Quit(2);
  133. }
  134. try {
  135.     tsOut = fso.OpenTextFile(outFile, 8, true, -1);//unicode encoding
  136. } catch (e) {
  137.     showError(e, 'can not write file ' + outFile);
  138.     WScript.Quit(3);
  139. }
  140. var oTasks = {
  141.     atEnd: false,
  142.     current: null,
  143.     moveNext: (function () {
  144.         var aIndex = [];
  145.         // var nextPage = 'http://www.zgshige.com/sg/index.shtml'; 可以自定义起始位置
  146.         var nextPage = 'http://www.zgshige.com/zcms/catalog/15112/pc/index_201.shtml';
  147.         var xhr = makeXHR();
  148.         var htmldoc = makeHtmldoc();
  149.         var oADO = makeADOStream();
  150.         var re = /<!-- 主体开始 -->[\S\s]*?(?=<!-- 主体结束 -->)/i;
  151.         var url = nextPage;
  152.         xhr.onReadyStateChange = function () {
  153.             if (xhr.readyState === 4) {
  154.                 if (200 === xhr.status) {
  155.                     var str = byte2str(oADO, xhr.responseBody, 'utf-8');
  156.                     var m = str.match(re);
  157.                     if (m) {
  158.                         htmldoc.body.innerHTML = m[0];
  159.                         var nodes = htmldoc.documentElement.getElementsByClassName('fc_ch1');
  160.                         for (nextPage = null, i = 0, l = nodes.length; i < l; ++i) {
  161.                             if (nodes[i].firstChild.nodeValue === '下一页') {
  162.                                 nextPage = parseURL(nodes[i].parentNode.getAttribute('href'), url);
  163.                                 break;
  164.                             }
  165.                         }
  166.                         if (!oCache[url]) {
  167.                             nodes = htmldoc.body.getElementsByClassName('fc-green text-uppercase');
  168.                             for (var i = 0, l = nodes.length; i < l; ++i) {
  169.                                 var item = parseURL(nodes[i].getAttribute('href'), url);
  170.                                 if (!oCache[item]) {
  171.                                     aIndex.push(item);
  172.                                 }
  173.                             }
  174.                             aIndex.push(url);
  175.                         }
  176.                         if (url = nextPage) {
  177.                             xhr.open('GET', url, true);
  178.                             // setRequestHeaders(xhr);
  179.                             xhr.send();
  180.                         } else {
  181.                             oTasks.atEnd = true;
  182.                             return false;
  183.                         }
  184.                     } else {
  185.                         nextPage = null;
  186.                         oTasks.atEnd = true;
  187.                         return false;
  188.                     }
  189.                 } else {
  190.                     nextPage = null;
  191.                     oTasks.atEnd = true;
  192.                     return false;
  193.                 }
  194.             }
  195.         };
  196.         xhr.open('GET', url, true);
  197.         setRequestHeaders(xhr);
  198.         xhr.send();
  199.         return function () {
  200.             return aIndex.shift();
  201.         };
  202.     })()
  203. };
  204. var maxThreads = 20,
  205.     aXhr = [],
  206.     i, l, task,
  207.     reIndex = /index.*html$/i;
  208. for (i = 0; i < maxThreads; ++i) {
  209.     aXhr.push(xhrWorkers());
  210. }
  211. while (!oTasks.atEnd) {
  212.     while (task = oTasks.moveNext()) {
  213.         if (reIndex.test(task)) {
  214.             tsCache.WriteLine(task);
  215.             WScript.StdOut.WriteLine(task);
  216.             continue;
  217.         }
  218.         while (!aXhr.length) {
  219.             WScript.Sleep(10);
  220.         }
  221.         aXhr.shift().job('GET', task, true);
  222.     }
  223.     WScript.Sleep(100);
  224. }
  225. while (task = oTasks.moveNext()) {
  226.     if (reIndex.test(task)) {
  227.         tsCache.WriteLine(task);
  228.         WScript.StdOut.WriteLine(task);
  229.         continue;
  230.     }
  231.     while (!aXhr.length) {
  232.         WScript.Sleep(10);
  233.     }
  234.     aXhr.shift().job('GET', task, true);
  235. }
  236. tsOut.close();
  237. tsCache.close();
  238. WScript.Quit(0);
复制代码
1

评分人数

TOP

本帖最后由 flashercs 于 2018-12-18 06:36 编辑

回复 70# lxh623

你表面是提取txt文本,实际上是用来当作html使用,对吧?这样每个子文件夹提取为一个txt文件,其实是个没有<head><body>的html文本,例如提取出的"2018-12-17.txt",将其重命名为"2018-12-17.txt.html"后用浏览器打开,就是个完整的html文档,浏览器自动添加<html><head><body>;我猜这应该是你的需求!
请保存为 "提取zgshige.bat"
  1. @echo off
  2. REM 设置htmlRoot = zgshige的html文件根目录
  3. set "htmlRoot=M:\zgshige"
  4. for /f "tokens=1 delims=:" %%A in ('findstr /n "#######*" %0') do more +%%A %0 >"%~dpn0.ps1"
  5. powershell.exe -ExecutionPolicy Bypass -File "%~dpn0.ps1" "%htmlRoot%"
  6. pause
  7. exit /b
  8. ################################################################
  9. # 保留html node
  10. param([string]$htmlRoot)
  11. [string]$scriptPath = [System.IO.Path]::GetDirectoryName($MyInvocation.MyCommand.Definition)
  12. $htmldoc = New-Object -ComObject htmlfile
  13. [void]$htmldoc.IHTMLDocument2_open()
  14. $htmldoc.IHTMLDocument2_write('<!DOCTYPE html><html><head><meta charset="utf-8" /><meta http-equiv="X-UA-Compatible" content="IE=edge"><title>Page Title</title><meta name="viewport" content="width=device-width, initial-scale=1"></head><body></body></html>')
  15. $htmldoc.IHTMLDocument2_close()
  16. [System.IO.Directory]::GetDirectories($htmlRoot, '*', [System.IO.SearchOption]::AllDirectories)|ForEach-Object {
  17.   $sw = [System.IO.StreamWriter]::new([System.IO.Path]::Combine($scriptPath, [System.IO.Path]::GetFileName($_) + '.txt'), $true, [System.Text.Encoding]::UTF8)
  18.   $sw.AutoFlush = $true
  19.   [System.IO.Directory]::GetFiles($_, '*.html')|ForEach-Object {
  20.     $m = [System.IO.File]::ReadAllText($_, [System.Text.Encoding]::UTF8) -match '<div class="text-center b-b b-2x b-lt">[\S\s]+?(?=<div class="p-sm">)'
  21.     if ($m) {
  22.       Write-Host "提取$_" -ForegroundColor Green
  23.       try {
  24.         $htmldoc.body.innerHTML = $Matches[0]
  25.         $div = $htmldoc.createElement('div');
  26.         # title
  27.         [void]$div.appendChild($htmldoc.body.getElementsByTagName('h3')[0])
  28.         # author
  29.         $divAuthor = $htmldoc.createElement('div')
  30.         [void]$divAuthor.appendChild($htmldoc.body.children[1].children[0].children[0])
  31.         $span = $divAuthor.appendChild($htmldoc.body.children[1].children[0].children[0])
  32.         [void]$span.removeAttributeNode($span.getAttributeNode('class'))
  33.         [void]$div.appendChild($divAuthor)
  34.         # signatureDiv
  35.         $divSignature = $htmldoc.createElement('div')
  36.         $nodeSig = $htmldoc.body.getElementsByClassName('signature')[0]
  37.         if ($null -ne $nodeSig) {
  38.           $span = $htmldoc.createElement('span')
  39.           [void]$span.appendChild($htmldoc.createTextNode($nodeSig.textContent))
  40.           [void]$divSignature.appendChild($span)
  41.         }
  42.         $nodeSigbox = $htmldoc.body.getElementsByClassName('signatureBox')[0]
  43.         if ($null -ne $nodeSigbox) {
  44.           $span = $htmldoc.createElement('span')
  45.           [void]$span.appendChild($htmldoc.createTextNode($nodeSigbox.textContent))
  46.           [void]$divSignature.appendChild($span)
  47.         }
  48.         [void]$div.appendChild($divSignature)
  49.         # content
  50.         $divContent = $htmldoc.body.getElementsByClassName('m-lg font14')[0]
  51.         [void]$divContent.attributes.removeNamedItem('class')
  52.         [void]$div.appendChild($divContent)
  53.         $sw.WriteLine($div.outerHTML)
  54.         Remove-Variable -Name div
  55.       }
  56.       catch {}
  57.     }
  58.   }
  59.   $sw.Close()
  60. }
  61. Remove-Variable -Name htmldoc
复制代码
1

评分人数

TOP

回复 75# lxh623

请把html文件放到M:\zgshige\test\目录下.

TOP

返回列表