您可以更改代码以不每次都重新加载页面,而是通过XMLHttpRequest
. 然后,您可以使用以下方法将响应解析为文档DOMParser
:
function request(callback) { // request will request the page content as text (without reloading)
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://your-url-here");
xhr.onload = function() {
callback(xhr.response);
};
xhr.send();
}
function next() { // next will be called each time instead of reloading
request(function(response) { // first we request the page
var doc = new DOMParser().parseFromString(response, "text/html"); // then we parse it as a document
var a = doc.getElementsByClassName("dispo"); // use doc instead of document (doc will be the newly requested document/page)
if (a.length > 0) {
for (let i = 0; i < a.length ; i++) {
if (a[i].textContent.length > 0) {
console.log(a[i].parentElement.textContent.substr(0,10) + " - " + a[i].textContent);
}
}
} else {
setTimeout(next, 60000); // if we didn't find anything, then call next after a minute
}
});
}
next();
笔记:
- 首先确保您当前在该页面上,这样您就不会收到 CORS 错误。
- 如果 url 有参数,您应该将它们作为 form发送。