問題描述
我想制作一個 Greasemonkey 腳本,當您在 URL_1 中時,該腳本會在后臺解析 URL_2 的整個 HTML 網頁,以便從中提取文本元素.
I want to make a Greasemonkey script that, while you are in URL_1, the script parses the whole HTML web page of URL_2 in the background in order to extract a text element from it.
具體來說,我想在后臺下載整個頁面的HTML代碼(一個爛番茄頁面)并將其存儲在一個變量中,然后使用getElementsByClassName[0]
以便從類名為critic_consensus"的元素中提取我想要的文本.
To be specific, I want to download the whole page's HTML code (a Rotten Tomatoes page) in the background and store it in a variable and then use getElementsByClassName[0]
in order to extract the text I want from the element with class name "critic_consensus".
我在 MDN 中找到了這個:XMLHttpRequest 中的 HTML所以,我最終得到了這個不幸的非工作代碼:
I've found this in MDN: HTML in XMLHttpRequest so, I ended up in this unfortunately non-working code:
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 中運行它時,它會顯示此錯誤消息:
It shows this error message when I run it in Firefox Scratchpad:
跨域請求被阻止:同源策略不允許讀取http://www.rottentomatoes.com/m/godfather/ 的遠程資源.這可以通過將資源移動到同一域或啟用 CORS.
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.
PS.我不使用爛番茄 API 的原因是 他們已經刪除了批評者的共識.
推薦答案
對于跨域請求,獲取的站點沒有幫助設置許可CORS 策略,Greasemonkey 提供 GM_xmlhttpRequest()
函數.(大多數其他用戶腳本引擎也提供此功能.)
For cross-origin requests, where the fetched site has not helpfully set a permissive CORS policy, Greasemonkey provides the GM_xmlhttpRequest()
function. (Most other userscript engines also provide this function.)
GM_xmlhttpRequest
明確設計為允許跨域請求.
GM_xmlhttpRequest
is expressly designed to allow cross-origin requests.
要獲取您的目標信息,請在結果上創建一個 DOMParser
.不要使用 jQuery 方法,因為這會導致加載無關的圖像、腳本和對象、減慢速度或使頁面崩潰.
To get your target information create a DOMParser
on the result. Do not use jQuery methods as this will cause extraneous images, scripts and objects to load, slowing things down, or crashing the page.
這里有一個完整的腳本來說明這個過程:
Here's a complete script that illustrates the process:
// ==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);
}
} );
這篇關于如何使用 XMLHttpRequest 在后臺下載 HTML 頁面并從中提取文本元素?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!