gpt4 book ai didi

javascript - 如何使用 XMLHttpRequest 在后台下载 HTML 页面并从中提取文本元素?

转载 作者:行者123 更新时间:2023-11-30 12:33:44 25 4
gpt4 key购买 nike

我想制作一个 Greasemonkey 脚本,当您在 URL_1 中时,该脚本会在后台解析 URL_2 的整个 HTML 网页,以便从中提取文本元素。

具体来说,我想在后台下载整个页面的 HTML 代码(一个 Rotten Tomatoes 页面)并将其存储在一个变量中,然后使用 getElementsByClassName[0] 以便从类名为“critic_consensus”的元素中提取我想要的文本。


我在 MDN 中找到了这个:HTML in XMLHttpRequest所以,我最终遇到了这个不幸的非工作代码:

var xhr = new XMLHttpRequest();
xhr.onload = function() {
alert(this.responseXML.getElementsByClassName(critic_consensus)[0].innerHTML);
}
xhr.open("GET", "http://www.rottentomatoes.com/m/godfather/",true);
xhr.responseType = "document";
xhr.send();

当我在 Firefox Scratchpad 中运行它时,它显示了这个错误消息:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://www.rottentomatoes.com/m/godfather/. This can be fixed by moving the resource to the same domain or enabling CORS.


附言。我不使用 Rotten Tomatoes API 的原因是 they've removed the critics consensus from it .

最佳答案

对于跨源请求,获取的站点没有帮助设置允许的 CORS policy , Greasemonkey 提供the GM_xmlhttpRequest() function . (大多数其他用户脚本引擎也提供此功能。)

GM_xmlhttpRequest 专为允许跨源请求而设计。

要获取目标信息,请在结果上创建一个 DOMParser。不要使用 jQuery 方法,因为这会导致加载无关的图像、脚本和对象,从而减慢速度或使页面崩溃。

这里有一个完整的脚本来说明这个过程:

// ==UserScript==
// @name _Parse Ajax Response for specific nodes
// @include http://stackoverflow.com/questions/*
// @require http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
// @grant GM_xmlhttpRequest
// ==/UserScript==

GM_xmlhttpRequest ( {
method: "GET",
url: "http://www.rottentomatoes.com/m/godfather/",
onload: function (response) {
var parser = new DOMParser ();
/* IMPORTANT!
1) For Chrome, see
https://developer.mozilla.org/en-US/docs/Web/API/DOMParser#DOMParser_HTML_extension_for_other_browsers
for a work-around.

2) jQuery.parseHTML() and similar are bad because it causes images, etc., to be loaded.
*/
var doc = parser.parseFromString (response.responseText, "text/html");
var criticTxt = doc.getElementsByClassName ("critic_consensus")[0].textContent;

$("body").prepend ('<h1>' + criticTxt + '</h1>');
},
onerror: function (e) {
console.error ('**** error ', e);
},
onabort: function (e) {
console.error ('**** abort ', e);
},
ontimeout: function (e) {
console.error ('**** timeout ', e);
}
} );

关于javascript - 如何使用 XMLHttpRequest 在后台下载 HTML 页面并从中提取文本元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26765311/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com