【问题标题】:How can I parse phantom.js output in php?如何在 php 中解析 phantom.js 输出?
【发布时间】:2019-01-22 14:39:40
【问题描述】:

我可以从命令行获取 phantom.js 请求的输出,并且输出是我所期望的。我想从 php 脚本调用 phantom.js,然后解析输出以查找某些内容。

我的 phantom.js 看起来像:

var page = require('webpage').create();
console.log('The default user agent is ' + page.settings.userAgent);
page.settings.userAgent = 'SpecialAgent';

page.open('https://www.aa.com/travelInformation/flights/status/detail?search=AA|1698|2019,1,23&ref=search', function(status) {
if (status !== 'success') {
    console.log('Unable to access network');
} else {
    var ua = page.evaluate(function() {
        return document.getElementById('aa-content-frame').innerHTML;
    });
    console.log(ua);
}
phantom.exit();
});

如果我从命令行运行以下命令:

phantomjs phantomjstest.js

我得到的输出类似于:

The default user agent is Mozilla/5.0 (Unknown; Linux x86_64) AppleWebKit/538.1 (KHTML, like Gecko) PhantomJS/2.1.1 Safari/538.1

<app-root-flight-status data="{&quot;queryString&quot;:&quot;AA|1698|2019,01,23&quot;,
&quot;bffUri&quot;:&quot;https://www.aa.com/flightinfo/v1.0/&quot;,
&quot;email&quot;:&quot;&quot;,
&quot;countryCode&quot;:&quot;&quot;,
&quot;phoneNumber&quot;:&quot;&quot;}" _nghost-c0="" ng-version="6.1.4"><router-outlet _ngcontent-c0=""></router-outlet><app-flight-details _nghost-c1=""><!----><!----><div _ngcontent-c1=""><!----><h1 _ngcontent-c1=""> Flight status</h1>

... blah blah blah ...

我想做的是从这样的 php 脚本中运行 phantom.js:

$response = exec('/usr/bin/phantomjs phantomjstest.js');

然后使用解析输出的代码继续执行 php 脚本。

当我执行我的 php 脚本时:

<?php

$response = exec('/usr/bin/phantomjs phantomjstest.js');

$query = mysqli_query($link, "INSERT INTO test (t_test) VALUES('11 - " . $response  . "')");

echo "Response = <br /><br />".$response;

?>

$response 似乎是空的。它不显示在屏幕上,仅将“11 -”添加到数据库中。我认为这是因为 phantomjstest.js 将“ua”记录到控制台。

我的问题是如何让 javascript 变量 ua 达到我可以在我的 php 脚本中解析它的程度。有什么想法吗?

【问题讨论】:

    标签: php html parsing phantomjs output


    【解决方案1】:

    PHP 的 exec 不返回输出。

    它用命令的输出填充第二个参数,例如:

    <?php
    $response = [];
    exec('/usr/bin/phantomjs phantomjstest.js', $response);
    
    var_dump($response);
    

    请看官方文档: http://php.net/manual/en/function.exec.php

    【讨论】:

    • 很高兴它成功了。欢迎来到 stackoverflow 社区 :)
    猜你喜欢
    • 2016-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多