dpw30157 2017-08-01 20:29
浏览 225

如何使用php-phantomjs在无头chrome中执行Javascript?

I'm trying to run a headless browser and run JS scripts (a bot) within it using but want to run it using php. Searching on Google, I found a implementation / wrapper of PhantomJS as php-phantomjs. Please bear with me, I'm very new to this stuff.

Here what I'm trying to do is to take screenshot of alert window (this is not necessary, but just to test if JS is executed and then the screenshot is taken.)

Here is my code:

// file: app.php

$client = PhantomJsClient::getInstance();
$client->isLazy();

$location = APP_PATH . '/partials/';

$serviceContainer = ServiceContainer::getInstance();
$procedureLoader = $serviceContainer->get('procedure_loader_factory')->createProcedureLoader($location);

$client->getProcedureLoader()->addLoader($procedureLoader);

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

$request->setViewportSize(1366, 768);
$request->setHeaders([
    'User-Agent' => 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.98 Safari/537.36'
]);

$request->setTimeout(5000);
$request->setUrl('https://www.google.co.in');

$request->setOutputFile(APP_PATH . '/screen.jpg');

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

Tried two custom scripts as given in the list here: http://jonnnnyw.github.io/php-phantomjs/4.0/4-custom-scripts/

// file: page_on_resource_received.partial, page_open.partial

alert("Hello");

OUTPUT: It just shows the page, not the alert window.

I repeat, Its not about taking screenshot, that's just to be sure that JS is executing. I just want to execute my JS scripts (better say bots) like:

var form = document.getElementById('form');
var event = new Event('submit');
form.dispatchEvent(event);

or maybe using jQuery and then return the output of that page to php as response or so. So, if there is any other way to run bots using php in a headless browser please mention that in your answers or comments.

  • 写回答

1条回答

  • dpjs2005 2017-08-02 05:15
    关注

    PhantomJS is headless, that is it doesn't have GUI. Therefore no window dialogs can be seen.

    Try writing custom text to an element instead of alert, like

    document.getElementById("#title").innerHTML = "It works!";
    
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!