在JavaScript中获取网页源码可以通过几种不同的方法实现,以下是一些常见的方法:
fetch
API 获取整个页面的HTML内容fetch(window.location.href)
.then(response => response.text())
.then(html => {
console.log(html); // 这里就是网页的源码
})
.catch(error => {
console.error('Error fetching the HTML:', error);
});
document.documentElement.outerHTML
获取当前文档的HTMLvar sourceCode = document.documentElement.outerHTML;
console.log(sourceCode); // 这里就是网页的源码
XMLHttpRequest
获取页面源码(较老的方法)var xhr = new XMLHttpRequest();
xhr.open('GET', window.location.href, true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText); // 这里就是网页的源码
}
};
xhr.send();
如果你遇到跨域问题,可以尝试以下方法:
如果你有一个Node.js后端,可以创建一个简单的代理来获取网页源码:
// server.js (Node.js)
const express = require('express');
const request = require('request');
const app = express();
app.get('/proxy', (req, res) => {
const url = req.query.url;
request(url).pipe(res);
});
app.listen(3000, () => {
console.log('Proxy server running on port 3000');
});
然后在JavaScript中调用这个代理:
fetch('http://localhost:3000/proxy?url=' + encodeURIComponent(window.location.href))
.then(response => response.text())
.then(html => {
console.log(html); // 这里就是网页的源码
})
.catch(error => {
console.error('Error fetching the HTML:', error);
});
这样,即使目标网站不允许跨域请求,你也可以通过自己的服务器来获取网页源码。
领取专属 10元无门槛券
手把手带您无忧上云