首页 > 解决方案 > 在一个窗口中循环不同的 URL

问题描述

有一组 URL。(URL1, URL2, URL3, ...)。我想打开一个新窗口,并在新窗口中打开这些 URL,从每个 URL 中逐个获取数据。我正在使用 newWindows.location.replace(URLs[i]); 更改窗口的href。我的问题是我找不到等待每个 URL 完全加载并收集数据的方法。

ps 我不是专业的程序员。我只是想使用 Violentmonkey 从网页内的表格中获取数据。表格是这样的:

<tableclass="fltlist_table">
... 
<tbodyid="flt1">
<tr>
<td>...</td>
</tr>
</tbody>
</table>

我的代码是这样的:

    fetch(newURL,fetchPara).then(function(response) {
if(response.ok) {
    response.formData().then(function(formData) {
    console.log(formData);
});
} else {
    console.log('Network request for products.json failed with response ' + response.status + ': ' + response.statusText);
}
})
.catch(function(err) {
    console.log("Error: "+ err);
});

好吧,我终于解决了这个问题。我的代码如下:

        //original nextPage.href is http, main page is https.
    newURL = nextPage.href.replace(/http/, "https");


    //New window
    newWindow = window.open(newURL, "FilghtWindow", "directories=no,resizable=no, width=400, height=400");

    newWindow.focus();

    var winLoaded = function(){
        //Collect rest
        finalData = GetData(newWindow.document);

        //Next
        nextPage =  newWindow.document.getElementsByClassName("schedule_down")[0];

        if (nextPage){
            newURL = nextPage.href.replace(/http/, "https");
            newWindow.location.replace(newURL);

        }else{
            //Finish
            console.log(finalData);
            newWindow.close();
        }

    }

    var winUnloaded = function(){
        setTimeout(function(){
            newWindow.onload= winLoaded;
            newWindow.onunload = winUnloaded;
        },0);
    }


    //add handle
    newWindow.onload= winLoaded;
    newWindow.onunload = winUnloaded;
}
enter code here

标签: javascriptloopswindow

解决方案


正如建议的那样,您最好发出 HTTP 请求而不是打开新窗口。这可以使用fetch()

const urls = ['url1', 'url2', 'url3'];

for (url in urls) {
  fetch(url)
    .then(response => {
      return response.text();
    })
    .then(text => {
      console.log(text);
    })
}

希望这可以帮助。祝你好运!


推荐阅读