【问题标题】:Can Greasemonkey fetch values from a paginated sequence of URL's?Greasemonkey 可以从 URL 的分页序列中获取值吗?
【发布时间】:2012-10-31 10:33:55
【问题描述】:

我想从https://play.google.com/store/account* 获取一个值,这使得用户页面通过其输出。例如:
/store/account?start=0&num=40,然后是/store/account?start=40&num=40等

现在,当我访问 https://play.google.com/apps 时,我希望 Greasemonkey 将 /store/account 页面中的值累加起来,然后在该页面上显示最终值。

下面列出的代码可以汇总来自/store/account 页面的我想要的值。但是,我想将代码插入到用于第二个 URL 的脚本中,这样我就可以在同一页面上添加它。

// ==UserScript==
// @name        Google Play 
// @require     http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js
// @grant       GM_setValue   
// @grant       GM_getValue  
// ==/UserScript==

var startParam      = location.search.match (/\bstart=(\d+)/i);
    if (startParam) {
        var totalPrice  = 0;
        var startNum    = parseInt (startParam[1], 10);
        if (startNum    === 0) {
            GM_setValue ("TotalPrice", "0");
        }
        else {
            totalPrice  = parseFloat (GM_getValue ("TotalPrice", 0) );
        }

        $("#tab-body-account .rap-link").each( function () {
            var price   = $(this).attr ("data-docprice").replace (/[^\d\.]/g, "");
            if (price) {
                price   = parseFloat (price);
                if (typeof price === "number") {
                    totalPrice += price;
                }
            }
        } );
        //console.log ("totalPrice: ", totalPrice.toFixed(2) );

        $('.tabbed-panel-tab').before (
            '<div id="SumTotal">*Combined Value: $'+ totalPrice.toFixed(2) +'</div>'
        );

        GM_setValue ("TotalPrice", "" + totalPrice);

        if ( $(".snippet.snippet-tiny").length ) {
            startNum       += 40;
            var nextPage    = location.href.replace (
                /\bstart=\d+/i, "start=" + startNum
            );
            location.assign (nextPage);
        }
    }

【问题讨论】:

    标签: javascript jquery greasemonkey mashup


    【解决方案1】:

    从页面/站点获取数据以进行混搭的基本方法是:

    1. 通过 AJAX 抓取:
      这适用于几乎所有页面,但不适用于通过 AJAX 加载所需内容的页面。有时,对于需要身份验证或限制推荐人的网站,它也会变得棘手。
      大多数情况下使用GM_xmlhttpRequest(),以允许跨域脚本。下面将详细介绍这种方法。

    2. 在&lt;iframe&gt; 中加载资源页面:
      这种方法适用于 AJAX 化页面,并且可以进行编码以让用户手动处理登录问题。但是,这是:速度更慢、资源更密集、代码更复杂。

      由于此问题的详细信息似乎不需要它,请参阅"How to get an AJAX get-request to wait for the page to be rendered before returning a response?" 了解有关此技术的更多信息。

    3. 使用网站的 API(如果有的话):
      唉,大多数网站都没有 API,所以这可能不适合您,但值得确保不提供 API。如果可用,API 通常是最好的方法。进行新的搜索/提问以了解有关此方法的更多详细信息。

    4. 模仿网站的 AJAX 调用,如果它为您想要的信息类型进行此类调用:
      此选项也不适用于大多数站点,但它可以是一种干净、有效的技术。进行新的搜索/提问以了解有关此方法的更多详细信息。


    通过支持跨域的 AJAX 从一系列网页中获取值:

    使用 GM_xmlhttpRequest() 加载页面,使用 jQuery 处理它们的 HTML。
    使用GM_xmlhttpRequest()的onload函数调用下一页,如有必要,不要尝试使用同步AJAX调用。

    核心逻辑从您的原始脚本移至 onload 函数内——除了不再需要记住 Greasemonkey 运行之间的值。

    这是一个完整的 Greasemonkey 脚本,其中包含一些状态和错误报告:

    // ==UserScript==
    // @name        _Total-value mashup
    // @include     https://play.google.com/apps*
    // @require     http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js
    // @grant       GM_addStyle
    // @grant       GM_xmlhttpRequest
    // ==/UserScript==
    
    var startNum        = 0;
    var totalValue      = 0;
    
    //--- Scrape the first account-page for item values:
    $("body").prepend (
        '<div id="gm_statusBar">Fetching total value, please wait...</div>'
    );
    scrapeAccountPage ();
    
    function scrapeAccountPage () {
        var accntPage   = 'https://play.google.com/store/account?start=0&num=40';
        accntPage       = accntPage.replace (/start=\d+/i, "start=" + startNum);
    
        $("#gm_statusBar").append (
            '<span class="gmStatStart">Fetching page ' + accntPage + '...</span>'
        );
    
        GM_xmlhttpRequest ( {
            method:     'GET',
            url:        accntPage,
            //--- getTotalValuesFromPage() also gets the next page, as appropriate.
            onload:     getTotalValuesFromPage,
            onabort:    reportAJAX_Error,
            onerror:    reportAJAX_Error,
            ontimeout:  reportAJAX_Error
        } );
    }
    
    function getTotalValuesFromPage (respObject) {
        if (respObject.status != 200  &&  respObject.status != 304) {
            reportAJAX_Error (respObject);
            return;
        }
    
        $("#gm_statusBar").append ('<span class="gmStatFinish">done.</span>');
    
        var respDoc     = $(respObject.responseText);
        var targetElems = respDoc.find ("#tab-body-account .rap-link");
    
        targetElems.each ( function () {
            var itmVal  = $(this).attr ("data-docprice").replace (/[^\d\.]/g, "");
            if (itmVal) {
                itmVal   = parseFloat (itmVal);
                if (typeof itmVal === "number") {
                    totalValue += itmVal;
                }
            }
        } );
        console.log ("totalValue: ", totalValue.toFixed(2) );
    
        if ( respDoc.find (".snippet.snippet-tiny").length ) {
            startNum       += 40;
            //--- Scrape the next page.
            scrapeAccountPage ();
        }
        else {
            //--- All done!  report the total.
            $("#gm_statusBar").empty ().append (
                'Combined Value: $' + totalValue.toFixed(2)
            );
        }
    }
    
    function reportAJAX_Error (respObject) {
        $("#gm_statusBar").append (
            '<span class="gmStatError">Error ' + respObject.status + '! &nbsp; '
            + '"' + respObject.statusText + '" &nbsp; &nbsp;'
            + 'Total value, so far, was: ' + totalValue
            + '</span>'
        );
    }
    
    //--- Make it look "purty".
    GM_addStyle ( multilineStr ( function () {/*!
        #gm_statusBar {
            margin:         0;
            padding:        1.2ex;
            font-family:    trebuchet ms,arial,sans-serif;
            font-size:      18px;
            border:         3px double gray;
            border-radius:  1ex;
            box-shadow:     1ex 1ex 1ex gray;
            color:          black;
            background:     lightgoldenrodyellow;
        }
        #gm_statusBar .gmStatStart {
            font-size:      0.5em;
            margin-left:    3em;
        }
        #gm_statusBar .gmStatFinish {
            font-size:      0.5em;
            background:     lime;
        }
        #gm_statusBar .gmStatError {
            background:     red;
            white-space:    nowrap;
        }
    */} ) );
    
    function multilineStr (dummyFunc) {
        var str = dummyFunc.toString ();
        str     = str.replace (/^[^\/]+\/\*!?/, '') // Strip function() { /*!
                .replace (/\s*\*\/\s*\}\s*$/, '')   // Strip */ }
                .replace (/\/\/.+$/gm, '') // Double-slash comments wreck CSS. Strip them.
                ;
        return str;
    }
    



    重要提示:不要忘记@include、@exclude 和/或@match 指令,因此您的脚本不会在每个页面和 iframe 上运行!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-14
      • 1970-01-01
      • 1970-01-01
      • 2019-04-01
      • 2023-01-24
      相关资源
      最近更新 更多