【问题标题】:How to execute Javascript in headless chrome using php-phantomjs?如何使用 php-phantomjs 在无头 chrome 中执行 Javascript?
【发布时间】:2017-08-01 20:29:28
【问题描述】:

我正在尝试运行无头浏览器并在其中运行 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 运行机器人,请在您的答案或 cmets 中提及。

【问题讨论】:

    标签: javascript php phantomjs php-phantomjs


    【解决方案1】:

    PhantomJS 是无头的,即它没有 GUI。因此看不到任何窗口对话框。

    尝试将自定义文本写入元素而不是警报,例如

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

    【讨论】:

    • 我尝试使用您的代码,但没有更改输出。我在程序中做错了吗?
    • 不要按原样使用,Google 页面上没有#title 元素。
    • 是的,我知道。我尝试根据需要进行一些修改,并在不在 Google 页面上的自定义 html 上进行了测试。你能给我一个你用来完成这个的代码的sn-p吗?
    猜你喜欢
    • 2013-12-10
    • 2021-08-09
    • 2019-09-15
    • 1970-01-01
    • 2017-01-03
    • 1970-01-01
    • 2015-08-11
    • 1970-01-01
    • 2023-01-14
    相关资源
    最近更新 更多