fetch
函数和 text()
方法。以下是一个简单的示例:,,“ javascript,fetch('https://example.com'), .then(response => response.text()), .then(sourceCode => console.log(sourceCode));,
“
要使用JavaScript获取网页源码,可以使用以下方法:
1、使用XMLHttpRequest
对象(适用于旧版浏览器):
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(xhr.responseText);
}
};
xhr.open("GET", "https://www.example.com", true);
xhr.send();
2、使用fetch
API(适用于现代浏览器):
fetch('https://www.example.com')
.then(response => response.text())
.then(html => console.log(html))
.catch(error => console.error('Error fetching the page:', error));
3、使用document.documentElement.innerHTML
(仅适用于当前页面):
var html = document.documentElement.innerHTML;
console.log(html);
注意:由于跨域限制,你可能无法直接获取其他域名下的网页源码,在这种情况下,你需要使用服务器端代码或者CORS代理来获取网页源码。
以上就是关于“js取网页源码”的问题,朋友们可以点击主页了解更多内容,希望可以够帮助大家!