如何将表格从其他网页加载到数组中?

时间:2015-09-01 00:52:09

标签: javascript arrays greasemonkey tampermonkey

我正在创建一个Greasemonkey / Tampermonkey脚本,它将一些统计信息放入一个数组中。

使用JavaScript,如何在后台加载网址(football.fantasysports.yahoo.com/f1/326198/pointsagainst?pos=QB)并创建包含前两列(RankTeam)的数组?

我遇到的问题是在后台完成所有这些工作,我认为我会使用AJAX。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:2)

对于静态页面(例如the one you linked),请使用GM_xmlhttpRequest()DOMParser来提取所需的元素。见下文。

对于动态页面 (AJAX驱动),请使用How to get an AJAX get-request to wait for the page to be rendered before returning a response?

中的技巧

此处一个完整的脚本,展示如何从第三方网页中提取信息并将其转换为数组变量:

// ==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);
}

答案 1 :(得分:0)

我想你想做点什么:

// ==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