[英]How to load a table, from another webpage, into an array?
我正在創建一個 Greasemonkey/Tampermonkey 腳本,它將一些統計信息放入一個數組中。
使用 JavaScript,我將如何使頁面在后台加載一個 URL( football.fantasysports.yahoo.com/f1/326198/pointsagainst?pos=QB )並創建一個包含前兩列( Rank
和Team
)的數組?
我遇到的問題是在后台執行所有這些操作,我想我會使用 AJAX。 任何幫助,將不勝感激。
對於靜態頁面(如您鏈接的頁面),請使用GM_xmlhttpRequest()
和DOMParser
來提取您想要的元素。 見下文。
對於動態頁面(AJAX 驅動) ,使用How to get an AJAX get-request 中的技術在返回響應之前等待頁面呈現?
這是一個完整的腳本,展示了如何從第三方頁面提取信息並將其轉換為數組變量:
// ==UserScript==
// @name _Grab stuff of a *static*, third-party web site.
// @include https://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://football.fantasysports.yahoo.com/f1/326198/pointsagainst?pos=QB&ntid=",
onload: parseResponse,
onerror: function (e) { console.error ('**** error ', e); },
onabort: function (e) { console.error ('**** abort ', e); },
ontimeout: function (e) { console.error ('**** timeout ', e); }
} );
function parseResponse (response) {
var parser = new DOMParser ();
/* IMPORTANT!
1) For older browsers, see
https://developer.mozilla.org/en-US/docs/Web/API/DOMParser
for a work-around.
2) jQuery.parseHTML() and similar is bad because it causes images, etc., to be loaded.
*/
var ajaxDoc = parser.parseFromString (response.responseText, "text/html");
var statRows = ajaxDoc.querySelectorAll ("#statTable0 > tbody > tr");
var newStatTable = $(statRows).map ( function () {
var tblRow = $(this);
var teamRank = parseInt (tblRow.find (".rank-indicator").text().trim(), 10);
var teamName = tblRow.find ("td:eq(1)").text().trim();
return [ [teamRank, teamName] ];
} ).get ();
/*-- newStatTable, is a 2-D array like:
[ [1, "Team A"],
[2, "Team B"],
[3, "Team C"],
//etc...
]
*/
console.log (newStatTable);
//alert (newStatTable);
}
我想你想做這樣的事情:
// ==UserScript==
// @name Fantasy Stuff
// @namespace http://football.fantasysports.yahoo.com/f1/326198/pointsagainst?pos=QB&ntid=
// @description An example of Fantasy Stuff
// @include *
// ==/UserScript==
var doc = document;
function T(t){
return doc.getElementsByTagName(t);
}
var tms = T('tbody')[0].getElementsByTagName('a'), teams = [];
for(var i=0,n=1,l=tms.length; i<l; i++,n++){
teams[n] = tms[i].text;
}
// teams array should hold results
console.log(teams); // in FireFox
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.