我正在尝试解析网站。该站点(我想)使用脚本和数据库来加载数据(动态?)。这是我的问题...我试图通过 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 页面上运行它们,就像它们在正确的浏览器环境中一样,但在当前的浏览器 session 中。
如果您在服务器端 (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
});
...获得全部内容。
关于javascript - 调用脚本后如何获取页面的 html 源代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54533900/