我一直在尝试从Hacker News获得最新新闻,尽管任何网站上的例子都可以。
这是我的代码:
let getHTML = function (url, callback) {
// Feature detection
if (!window.XMLHttpRequest) return;
// Create new request
let xhr = new XMLHttpRequest();
// Setup callback
xhr.onload = function () {
if (callback && typeof (callback) === 'function') {
callback(this.responseXML);
}
};
// Get the HTML
xhr.open('GET', url);
xhr.responseType = 'document';
xhr.send();
};
getHTML('https://news.ycombinator.com/news', function (response) {
let someElem = document.querySelector('#someElementFromMyPage');
let someOtherElem = response.querySelector('#someElementFromOtherPage');
someElem.innerHTML = someOtherElem.innerHTML;
});
此应显示其他页面 中的元素,并将其带到 我的页面 。
答案 0 :(得分:1)
运行代码时,在浏览器开发工具控制台(more details here)中收到CORS错误。
问题
基本上,目标网站(https://news.ycombinator.com/news)限制了浏览器如何请求它。并且浏览器遵守并遵守此限制。
X-Frame-Options: DENY
和X-XSS-Protection: 1 mode=block
浏览器不允许您读取JS代码中的请求,所以会出现错误。解决方案
有许多解决CORS错误的方法,您可以自己进行研究:
通过代理服务器的漏斗请求,通过另一个剥离烦人的CORS标头的服务器路由CORS请求。 maybe this?
运行用于网络爬网的服务器,服务器不必像浏览器那样尊重标头,因此您可以获取任何内容。 maybe try this
在浏览器中进行抓取越来越困难,因此您需要使用其他解决方案从其他站点获取内容。
希望这会有所帮助!