我正在尝试运行无头浏览器并在其中运行 JS 脚本(机器人),但想使用 php 运行它。在 Google 上搜索,我发现了 PhantomJS 的实现/包装器为 php-phantomjs。请耐心等待,我对这些东西很陌生。
这里我要做的是对警报窗口进行截图(这不是必需的,只是为了测试是否执行了JS然后截图。)
这是我的代码:
// 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);
尝试了此处列表中给出的两个自定义脚本:http: //jonnnnyw.github.io/php-phantomjs/4.0/4-custom-scripts/
// file: page_on_resource_received.partial, page_open.partial
alert("Hello");
输出:它只显示页面,而不是警报窗口。
我再说一遍,这不是截图,只是为了确保 JS 正在执行。我只想执行我的 JS 脚本(最好是机器人),例如:
var form = document.getElementById('form');
var event = new Event('submit');
form.dispatchEvent(event);
或者也许使用jQuery,然后将该页面的输出作为响应返回给php。因此,如果有任何其他方式可以在无头浏览器中使用 php 运行机器人,请在您的答案或评论中提及。