![](/img/trans.png)
[英]How to get all html data after all scripts and page loading is done? (puppeteer)
[英]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.