0

我正在创建一个 Greasemonkey 脚本,我在其中计算六个变量(时间、移动、滚动、sav、prin、book 和 url)。

我需要将这些变量的数据发送到我的 PHP 页面,以便可以使用 WAMP 服务器将这些数据插入到 MySQL 表中。

拜托,任何人都可以给它确切的代码,因为我对这一切都不熟悉吗?

我的 Greasemonkey 脚本是:

{var ajaxDataObj = {
    s:      sav,
    p:      prin,
    b:      book,
    t:      finalTime,
    u:      url,
    a:      totalScroll,
    b:      tot
};

var serializedData  = JSON.stringify (ajaxDataObj);

GM_xmlhttpRequest ( {
    method: "POST",
    url:    "localhost/anuja/greasemonkey.php",
    data:   serializedData,
    headers: {
        "Content-Type": "application/json",
        "User-Agent": "Mozilla/5.0",    // If not specified, navigator.userAgent will be used.
        "Accept": "text/xml"            // If not specified, browser defaults will be used.
} }


而php方面是:

$jsonData   = json_decode($HTTP_RAW_POST_DATA);

echo jsonData.u;


这段代码没有运行.. 另外我尝试检查我的变量u是否已通过使用jsonData.u,但它只是回显“jsonData.u”。

4

1 回答 1

-1

我只是创建用户脚本以使 Greasemonkey 从打开的网页中抓取数据并将参数 POST 到托管在我的本地 XAMPP 服务器上的 PHP 脚本,该服务器可以运行本地 Python 脚本来自动化工作。

这也是从 Javascript 呈现的页面中抓取数据的一种很酷的方法,这对于 Python 抓取工具来说很难,甚至比 Selenium 更好:P

&参数在此 PHP 示例 url 中被分隔:

http://www.sciencedirect.com/search?qs=Vascular%20stent&authors=&pub=&volume=&issue=&page=&origin=home&zone=qSearch&offset=1200

GM脚本部分:

// @grant        GM_xmlhttpRequest
unsafeWindow.sendPhp2Py = function(){
    //var ytitle = 'Youtube - ' + document.querySelector('div.yt-user-info').textContent.trim();
    var yurl = document.location.href;
    //console.info(ytitle);
    //console.info(yurl);
    var ret = GM_xmlhttpRequest({
        method: "POST",
        url: "http://localhost/php_run_py.php",
        //data: "ytitle="+ ytitle + "&yurl="+ yurl,
        data: "yurl="+ yurl,
        headers: {
            "Content-Type": "application/x-www-form-urlencoded"
        },
        onload: function(response) {
            console.log(response);
            // readyState 4 = complete
            // status = 200 OK
            if(response.readyState == 4 && response.status == 200){
                document.querySelector('#myPhpPyBtn').textContent = 'Sent to PHP!';
            }
        },
        onerror: function(e){
            console.log(e);
            document.querySelector('#myPhpPyBtn').textContent = 'PHP not connected';
        }
    });
};

PHP 脚本:

<?php
    echo $_POST['yurl'];
//传递多个参数如下可以行得通 参数里包含空格哦也可以!!赞 Multiple parameters pass
    //echo shell_exec("python test.py \"".$_POST['ytitle']."\" \"".$_POST['yurl']."\"");
    //echo shell_exec("python GreaseMonkey_Php_Youtube_srt_generator.py ".$_POST['yurl']);
//更安全 Safer
    //system(escapeshellcmd("python test.py \"".$_POST['ytitle']."\" \"".$_POST['yurl']."\""));
    system(escapeshellcmd("python GreaseMonkey_Php_Youtube_srt_generator.py ".$_POST['yurl']));
?>

Python测试脚本:

#coding=utf-8
import sys
f = open("test.txt", "a+")
f.write(sys.argv[1] + "\n" + sys.argv[2]+ "\n") 
f.close()
print ("some output")

希望它可以帮助!

于 2017-11-26T04:22:04.653 回答