我正在尝试解析网站。该站点(我想)使用脚本和数据库从中动态加载数据。这是我的问题...我试图通过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;
}
所有这些功能都无法正常运行。
答案 0 :(得分:1)
这实际上并不实用-您试图加载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
});
...获得全部信息。