繁体   English   中英

调用所有脚本后,如何获取页面的html源?

[英]How to get html source of page, after all it scripts was called?

我正在尝试解析网站。 该站点(我想)使用脚本和数据库从中动态加载数据。 这是我的问题...我试图通过C#(不幸的是我现在无法访问代码)或JS来获取数据。 而且似乎C#和JS都只获得站点的模板,但不要等到所有脚本执行完毕。 所以这是我的问题,有没有办法获取所有html源代码? 也许以某种方式调用脚本。 还是发出请求,等待10秒钟,然后将源html数据写入变量?

这是我的JS代码。

function request(link)
{

    var xhr = new XMLHttpRequest();

    xhr.open('GET', link, true);

    xhr.onreadystatechange = function() . 
        {console.log(xhr.readyState);};

    xhr.send();

    let data  = xhr.responseText;

    var tempDiv = document.createElement('div');
    tempDiv.innerHTML = data.replace(/<script(.|\s)*?\/script>/g, 
        '');

    return tempDiv;
}

function loadFile(url, timeout, callback) 
{
    var args = Array.prototype.slice.call(arguments, 3);
    var xhr = new XMLHttpRequest();
    xhr.ontimeout = function () {
        console.error("The request for " + url + " timed out.");
        };
    xhr.onload = function() {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                callback.apply(xhr, args);
            } else {
                console.error(xhr.statusText);
            }
        }
    };
    xhr.open("GET", url, true);
    xhr.timeout = timeout;
    xhr.send(null);

    let data  = xhr.responseText;
    return data;
}

function showMessage (message) {
    console.log(message + this.responseText);
}

function include(scriptUrl)
{
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("GET", scriptUrl);
    xmlhttp.onreadystatechange = function()
    {
        if ((xmlhttp.status == 200) && (xmlhttp.readyState == 4))
       {
            eval(xmlhttp.responseText);
       }
    };
    xmlhttp.send();

    let data  = JSON.parse(xmlhttp.responseText);

    var tempDiv = document.createElement('div');
    tempDiv.innerHTML = data.replace(/<script(.|\s)*?\/script>/g, 
     '');

    return tempDiv;
}

所有这些功能都无法正常运行。

这实际上并不实用-您尝试加载HTML页面,所有关联的脚本,然后在HTML页面上运行它们,就像它们在适当的浏览器环境中一样,但是在您当前的浏览器会话中。

如果您是在服务器端(NodeJS)上运行的,这种事情对于jsdom库是可行的,因为它模拟了浏览器的行为: https : //github.com/jsdom/jsdom 所以你可以做

JSDOM.fromURL("https://example.com/", { runScripts: "dangerously" }).then(dom => {
   console.log(dom.serialize()); //turn the page back into HTML
});

...得到全部。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM