【问题标题】:Correct Way to Pass Script to PhantomJS via PHP-PhantomJS?通过 PHP-PhantomJS 将脚本传递给 PhantomJS 的正确方法?
【发布时间】:2017-03-05 02:06:18
【问题描述】:

我正在学习 PhantomJS 和 PHP-PhantomJS。我想将脚本传递给 PhantomJS。

目前我正在尝试这个:

   $client->getEngine()->addOption('/Applications/myWebApp/js/phantomtest.js');
    $request = $client->getMessageFactory()->createRequest('http://www.jonnyw.me/', 'GET');

    $response = $client->getMessageFactory()->createResponse();
    $client->send($request, $response);
    if ($response->getStatus() === 200) {
        echo $response->getContent();
    }

在调用 $client->send($request, $response) 后,我得到了一个空的 $response 对象。

Here's the contents of my test script ('phantomtest.js'):

var page = require('webpage').create();
page.open('http://www.jonnyw.me', function(status) {
  console.log("Status: " + status);
  if(status === "success") {
    page.render('example.png');
  }
  phantom.exit();
});

【问题讨论】:

  • 看起来很有趣,但我宁愿只使用反引号
  • @pguardiario,为此使用反引号的正确方法是什么?
  • <?php `/usr/bin/phantomjs /path/to/script.js` ?>exec
  • 确保你抓住了价值:<?php $response = `phantomjs /path/to/script.js` ?>
  • 我不知道你能做到。

标签: web-scraping phantomjs php-phantomjs


【解决方案1】:

我认为这一定是文档中的相关页面:http://jonnnnyw.github.io/php-phantomjs/4.0/4-custom-scripts/

这是有效的代码:

在 PHP 中:

    $location = '/Applications/myWebApp/js/';
    $serviceContainer = ServiceContainer::getInstance();

    $procedureLoader = $serviceContainer->get('procedure_loader_factory')
            ->createProcedureLoader($location);
    $client->getProcedureLoader()->addLoader($procedureLoader);

    $request = $client->getMessageFactory()->createRequest();
    $client->setProcedure('phantomJStest');

    $response = $client->getMessageFactory()->createResponse();

    $client->send($request, $response);

    if (($response->getStatus() === 200) || ($response->getStatus() == 'success')){
        // Dump the requested page content
        echo $response->getContent();
    }

在proc文件phantomJStest.proc:

phantom.onError = function (msg, trace) {
    console.log(JSON.stringify({
      "status": msg
    }));
    phantom.exit(1);
};

var system = require('system');
var uri = "http://www.jonnyw.me";

var page = require('webpage').create();
page.open(uri, function (status) {
    console.log(JSON.stringify({
      "status": status
    }));

    if (status === "success") {
        page.render('example.png');
    }
    phantom.exit(1);
});

【讨论】:

  • 请将链接中的信息添加到您的答案中(以防该页面稍后消失)
  • @Vaviloff 这是一整页信息。在这里发帖太多了?
  • 当然不是,只需粘贴代码示例即可从该库运行自定义脚本。一定有办法做到这一点,对吧?
  • @Vaviloff 昨天我没有让它工作,即使有文档 - 文档似乎缺少一步,或者至少没有让它足够明显。但从那时起,我就开始工作了。根据您的要求,我正在使用工作代码更新我的答案。
  • 很高兴您找到了答案并在这里提出,赞!希望以后会对此感到疑惑的人会找到您的答案。 ...但是我的上帝,这个库是不是被过度设计了!
猜你喜欢
  • 2018-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多