因工作需要,需要定期從某頁面下載多個文檔,是體力活。
想用chrome擴展,找了幾個不行。原因是:
1、有的擴展識別不了鏈接,因為鏈接是形如:jsp?XXX=XXX的形式
2、有的擴展能批量打開鏈接,但打開的太快了或其他原因,觸發了驗證碼。
想用chromedp模擬操作,感覺大材小用,也懶得費事。
決定還是用比較簡單的chrome console
參考以下代碼(https://bbs.csdn.net/topics/392177700?list=31152598)
(function () { var arr = ["https://www.baidu.com/","http://url2","http://url3"]; var nw = window.open(); var i = 0; function op() { console.log(arr[i]); nw.location = arr[i]; i++; if (i<arr.length) setTimeout(op, 5000); } op(); })();
我寫的代碼如下:其中用了正則/owner=/.test(aa[i].href)匹配鏈接:
(function () { var aa=$("a"); var arr=[]; for(var i=0;i<aa.length;i++){ if(/owner=/.test(aa[i].href)){ arr.push(aa[i].href); } } var nw = window.open(); var i = 0; function op() { console.log(arr[i]); nw.location = arr[i]; i++; if (i<arr.length) setTimeout(op, 5000); } op(); })();
因為我在頁面上用代碼訪問鏈接時,會直接下載word。所以在啟動腳本的時候,chrome會提示:想要下載多個文件? 允許就可以了。
實際使用中沒有觸發驗證碼,終於不用一個個點擊鼠標右鍵另存為了。
后來發現這里有一個疑惑之處:我用的是$("a"),而不是$$("a"),竟然也能成功!
更好的選擇辦法:可以不用正則表達式,用“子串匹配屬性選擇器”好像更方便些,如:$("a[href*=要匹配的部分URL內容]")
補充:之前用以下代碼,chrome只能打開一個新窗口
var nw =window.open("https://www.sohu.com","one"); var nw1 =window.open("https://www.cnblogs.com","two");
后來發現,瀏覽器為了安全考慮是不會讓瀏覽器一次打開多個窗口的,不過如果用戶需要是可以在瀏覽器里面進行設置的,chrome中chrome://settings/content/popups,設置為允許即可。(參考:https://blog.csdn.net/Tayshin/article/details/73614854)