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!";
    
    评论

报告相同问题?

悬赏问题

  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题