用chrome console实现自动化操作网页

因为chrome console只能访问当前页的上下文(以及chrome扩展的上下文),无法访问其他标签页面的上下文,所以局限性较大,仅适用于一些较简单的操作

经实践,可以在chrome的一个标签页的console中执行javascript,对于window.open打开的新标签页的上下文进行操作,详见情况4

情况1:页面上有多个url链接,每个url的href中包含有 XXXX 字样,想要一次全部点开

参考代码:

var a = $$("a[href*='javaScript:openFullWindowHaveBarForWFList']")
a.forEach(function(w){w.click()})

情况2:这些链接中都包含6个数字,想要提取出来并组成新的URL后,全部点开

参考代码:

var a = $$("a[href*='javaScript:openFullWindowHaveBarForWFList']")
var id =[]
a.forEach(function(i){id.push(String(i).match(/[0-9]{6}/)[0])})
id.forEach(function(j){var  nw = window.open();nw.location = "http://192.168.132.80/workflow/request/ManageRequestNoForm.jsp?fromFlowDoc=&requestid=" + j +"&isrequest=0&isovertime=0&isaffirmance=&reEdit=1&seeflowdoc=0&isworkflowdoc=0&isfromtab=false";})

这里用window.open打开了新窗口,如果能获取新窗口的上下文,就可以真正实现自动化了。可惜不行。只有用chrome扩展才行。

 情况3:参考上一篇文章,打开新窗口用于循环访问URL,如果URL对应的zip或DOC等,则可以实现批量下载。

参考代码:

(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();
})();

 情况4:所谓的“真正实现自动化”;如:先在新标签页中打开baidu输入关键词“美女”,提交搜索;再打开sohu在搜索框中输入“野兽”

参考:https://www.cnblogs.com/laden666666/p/5544572.html    https://www.cnblogs.com/yanggl/p/10211930.html 修改 chrome浏览器的跨域设置

然而我在chrome 77 上设置后还是没办法获取另一个标签页的上下文。

最后只能退而求其次,不跨域(因为我们通常只针对某个网站内部进行自动化操作),所以我在情况4题目上加了“所谓的”三个字

这里将情况4的任务变更为:先在新标签页中打开baidu输入关键词“美女”,提交搜索;再打开baidu搜索框输入“野兽”

可以考虑延时函数

function sleep(delay) {
    for(var t = Date.now(); Date.now() - t <= delay;);
}

代码如下(确保代码在badu.com的console中执行,即保持不跨域):

var nw = window.open();
nw.location ="https://baidu.com";
(pageok = function(){
    if(nw.document.getElementById('kw') != null){
        //做你想做的的事
      nw.document.getElementById('kw').value ="美女";

    }
    else{
        //500毫秒轮询一次
        setTimeout(pageok , 500)
    }
})();
(pageok1 = function(){
    if(nw.document.getElementById('su') != null){
        //做你想做的的事
      nw.document.getElementById('su').click();
      setTimeout(function(){nw.document.getElementById('kw').value ="野兽"},5000);

    }
    else{
        //500毫秒轮询一次
        setTimeout(pageok1 , 500)
    }
})();
原文地址:https://www.cnblogs.com/pu369/p/12022911.html