Получать запросы с сайта и получать ответ? - PullRequest
4 голосов
/ 15 июля 2011

Я пытаюсь отслеживать веб-сайт ( www.bidcactus.com ). Находясь на веб-сайте, я открываю Firebug, перехожу на вкладку net и нажимаю вкладку XHR.

Я хочу взять ответы на запросы и сохранить их в базе данных mySql (у меня на компьютере работает локальная база данных (XAMPP).

Мне было сказано делать разные вещи, в основном с использованием jQuery или JavaScript, но у меня тоже нет опыта, поэтому мне было интересно, может ли кто-нибудь помочь мне здесь.

Кто-то предложил мне эту ссылку Использование Greasemonkey и jQuery для перехвата данных JSON / AJAX со страницы и их обработки

Он также использует Greasemonkey, о котором я мало что знаю ...

Заранее спасибо за любую помощь

Пример / более подробно:
При мониторинге отправленных запросов (через firebug) я вижу ниже

http://www.bidcactus.com/CactusWeb/ItemUpdates?rnd=1310684278585
The response of this link is the following:
{"s":"uk5c","a":[{"w":"MATADORA","t":944,"p":5,"a":413173,"x":10},   
{"w":"1000BidsAintEnough","t":6,"p":863,"a":413198,"x":0}, 
{"w":"YourBidzWillBeWastedHere","t":4725,"p":21,"a":413200,"x":8}, 
{"w":"iwillpay2much","t":344,"p":9,"a":413201,"x":9}, 
{"w":"apcyclops84","t":884,"p":3,"a":413213,"x":14}, 
{"w":"goin_postal","t":165,"p":5,"a":413215,"x":12}, 
{"w":"487951","t":825,"p":10,"a":413218,"x":6}, 
{"w":"mishmash","t":3225,"p":3,"a":413222,"x":7}, 
{"w":"CrazyKatLady2","t":6464,"p":1,"a":413224,"x":2}, 
{"w":"BOSS1","t":224,"p":102,"a":413230,"x":4}, 
{"w":"serbian48","t":62,"p":2,"a":413232,"x":11}, 
{"w":"Tuffenough","t":1785,"p":1,"a":413234,"x":1}, 
{"w":"apcyclops84","t":1970,"p":1,"a":413240,"x":13}, 
{"w":"Tuffenough","t":3524,"p":1,"a":413244,"x":5}, 
{"w":"Cdm17517","t":1424,"p":1,"a":413252,"x":3}],"tau":"0"}

Я понимаю, что это за информация, и думаю, что смогу отформатировать ее самостоятельно, однако веб-сайт случайным образом создает новые запросы.
Пример http://www.bidcactus.com/CactusWeb/ItemUpdates?rnd=XXXXXXXXXXXX
и я не уверен, как он их создает.

Поэтому мне нужно получить ответ на все запросы об обновлении элементов и отправить информацию в базу данных mysql.

Ответы [ 2 ]

3 голосов
/ 24 июля 2011

ОК, вот рабочий код, несколько настроенный для этого сайта (первая полоса, без учетной записи, только).

Инструкция по применению:

  1. Установите скрипт GM.Обратите внимание, что на данный момент это только Firefox.

  2. Наблюдайте, как он работает в консоли Firebug, и настройте раздел фильтра (с четкой маркировкой), чтобы нацелиться на интересующие вас данные. (Возможновесь массив a?)

    Обратите внимание, что для запуска перехвата ajax может потребоваться несколько секунд после запуска перехвата ajax.

  3. Настройте вашвеб-приложение и сервер для получения данных.Сценарий отправляет JSON, поэтому PHP, например, будет получать данные следующим образом:

    $jsonData   = json_decode ($HTTP_RAW_POST_DATA);
    
  4. Укажите сценарий на свой сервер.

  5. Вуаля.Она готова.


/******************************************************************************
*******************************************************************************
**  This script intercepts ajaxed data from the target web pages.
**  There are 4 main phases:
**      1)  Intercept XMLHttpRequest's made by the target page.
**      2)  Filter the data to the items of interest.
**      3)  Transfer the data from the page-scope to the GM scope.
**          NOTE:   This makes it technically possibly for the target page's
**                  webmaster to hack into GM's slightly elevated scope and
**                  exploit any XSS or zero-day vulnerabilities, etc.  The risk
**                  is probably zero as long as you don't start any feuds.
**      4)  Use GM_xmlhttpRequest () to send the data to our server.
*******************************************************************************
*******************************************************************************
*/
// ==UserScript==
// @name            _Record ajax, JSON data.
// @namespace       stackoverflow.com/users/331508/
// @description     Intercepts Ajax data, filters it and then sends it to our server.
// @include         http://www.bidcactus.com/*
// ==/UserScript==

DEBUG   = true;
if (DEBUG)  console.log ('***** Script Start *****');


/******************************************************************************
*******************************************************************************
**  PHASE 1 starts here, this is the XMLHttpRequest intercept code.
**  Note that it will not work in GM's scope.  We must inject the code to the
**  page scope.
*******************************************************************************
*******************************************************************************
*/
funkyFunc   = ( (<><![CDATA[

    DEBUG           = false;
    //--- This is where we will put the data we scarf. It will be a FIFO stack.
    payloadArray    = [];   //--- PHASE 3a

    (function (open) {
        XMLHttpRequest.prototype.open = function (method, url, async, user, pass)
        {
            this.addEventListener ("readystatechange", function (evt)
            {
                if (this.readyState == 4  &&  this.status == 200)  //-- Done, & status "OK".
                {
                    var jsonObj = null;
                    try {
                        jsonObj = JSON.parse (this.responseText);   // FF code.  Chrome??
                    }
                    catch (err) {
                        //if (DEBUG)  console.log (err);
                    }
                    //if (DEBUG)  console.log (this.readyState, this.status, this.responseText);

                    /******************************************************************************
                    *******************************************************************************
                    **  PHASE 2:    Filter as much as possible, at this stage.
                    **              For this site, jsonObj should be an object like so:
                    **                  { s="1bjqo", a=[15], tau="0"}
                    **              Where a is an array of objects, like:
                    **                  a   417387
                    **                  p   1
                    **                  t   826
                    **                  w   "bart69"
                    **                  x   7
                    *******************************************************************************
                    *******************************************************************************
                    */
                    //if (DEBUG)  console.log (jsonObj);
                    if (jsonObj  &&  jsonObj.a  &&  jsonObj.a.length > 1) {
                        /*--- For demonstration purposes, we will only get the 2nd row in
                            the `a` array. (Probably stands for "auction".)
                        */
                        payloadArray.push (jsonObj.a[1]);
                        if (DEBUG)  console.log (jsonObj.a[1]);
                    }
                    //--- Done at this stage!  Rest is up to the GM scope.
                }
            }, false);

            open.call (this, method, url, async, user, pass);
        };
    } ) (XMLHttpRequest.prototype.open);
]]></>).toString () );


function addJS_Node (text, s_URL)
{
    var scriptNode                      = document.createElement ('script');
    scriptNode.type                     = "text/javascript";
    if (text)  scriptNode.textContent   = text;
    if (s_URL) scriptNode.src           = s_URL;

    var targ    = document.getElementsByTagName('head')[0] || d.body || d.documentElement;
    targ.appendChild (scriptNode);
}

addJS_Node (funkyFunc);


/******************************************************************************
*******************************************************************************
**  PHASE 3b:
**  Set up a timer to check for data from our ajax intercept.
**  Probably best to make it slightly faster than the target's
**  ajax frequency (about 1 second?).
*******************************************************************************
*******************************************************************************
*/
timerHandle = setInterval (function() { SendAnyResultsToServer (); }, 888);

function SendAnyResultsToServer ()
{
    if (unsafeWindow.payloadArray) {
        var payload     = unsafeWindow.payloadArray;
        while (payload.length) {
            var dataRow = JSON.stringify (payload[0]);
            payload.shift ();   //--- pop measurement off the bottom of the stack.
            if (DEBUG)  console.log ('GM script, pre Ajax: ', dataRow);

            /******************************************************************************
            *******************************************************************************
            **  PHASE 4: Send the data, one row at a time, to the our server.
            **  The server would grab the data with:
            **      $jsonData   = json_decode ($HTTP_RAW_POST_DATA);
            *******************************************************************************
            *******************************************************************************
            */
            GM_xmlhttpRequest ( {
                method:     "POST",
                url:        "http://localhost/db_test/ShowJSON_PostedData.php",
                data:       dataRow,
                headers:    {"Content-Type": "application/json"},
                onload:     function (response) {
                                if (DEBUG)  console.log (response.responseText);
                            }
            } );
        }
    }
}


//--- EOF



Разное примечания:

  1. Я протестировал его на главной странице этого сайта, не входя в систему (я не собираюсь создавать там учетную запись).

  2. Я протестировал с AdBlock , FlashBlock , NoSCript и RequestPolicy - все в полном объеме.JS был включен для bidcactus.com (должно быть), но не для других.Включение всего этого не должно вызывать побочных эффектов, но если это произойдет, я не буду его отлаживать.

  3. Код, подобный этому, должен быть настроен для сайтаи как вы просматриваете указанный сайт 1 .Это зависит от вас, чтобы сделать это.Надеюсь, код достаточно документирован.

  4. Наслаждайтесь!



1 В основном: директивы @include и @exclude, выбор и фильтрация данных JSON, а также необходимость блокировки iFrames.Также рекомендуется, чтобы 2 DEBUG переменные (одна для области GM и одна для области страницы) были установлены на false, когда настройка будет выполнена.

0 голосов
/ 15 июля 2011

Этого нельзя достичь с помощью ajax-запроса javascript / jquery из-за Одинаковая политика происхождения

У меня не было опыта работы с greasemonkey, через

...