如何解析作为POST请求结果的HTML页面(在PHP中使用curl、JSONPath、Xpath)?

How to parse a HTML page that is the POST request result (using curl, JSONPath, Xpath in PHP)?

我需要解析这个网页....

http://monitorps.sardegnasalute.it/monitorps/MonitorServlet?page=carLavoroPresidi&tipoProntoSoccorso=TUTTI&codiceAziendaSanitaria=200102&idPresidio=102MAD02&indirizzo=null&idProntoSoccorso=30

... 使用 PHP 提取列 "ROSSO"、GIALLO"、"VERDE" 和 "BIANCO" 下的 table 中的数字.

(注意:如果您尝试浏览该页面,您可能会在该页面中看到不同的值......没关系..,它会动态变化......)

这些值是网页内的POST请求结果。

这是我用来使用 curl 发送 POST 请求的 PHP 代码,然后解析 JSON 响应(使用 Skyscanner JSON 路径.. 它在我的代码中运行良好 .. ),尝试使用 XPath 解析提取值。

<?php
    include "./tmp/vendor/autoload.php";

    $ch = curl_init();

    curl_setopt_array($ch, array(
      CURLOPT_URL => "http://monitorps.sardegnasalute.it/monitorps/MonitorServlet",
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => "",
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 30,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => "POST",
      CURLOPT_POSTFIELDS => "idMacroArea=null&codiceAziendaSanitaria=200102&idAreaVasta=null&idPresidio=102MAD02&idProntoSoccorso=30&tipoProntoSoccorso=TUTTI&vicini=null&xhr=true",
      CURLOPT_HTTPHEADER => array(
        "cache-control: no-cache",
        "content-type: application/x-www-form-urlencoded"
      ),
    ));

    $server_output = curl_exec ($ch);

    curl_close ($ch);

    $jsonObject = new JsonPath\JsonObject($server_output);

    $jsonPathExpr = '$..view';

    $res = $jsonObject->get($jsonPathExpr);
    print $res[0];

    $dom = new DOMDocument();
    @$dom->loadHTML(json_encode($res[0]));

    $xpath = new DOMXPath($dom);

    $xpath_for_parsing = '/html/body/div[1]/div/div/div/table/tbody/tr[2]/td[4]';

    $colorWaitingNumber = $xpath->query($xpath_for_parsing);
    $theValue =  'N.D.';
    foreach( $colorWaitingNumber as $node )
    {
      $theValue = $node->nodeValue;
    }

    print $theValue;

    ?>

结果如下图

其中 table 是我的代码中命令的结果...

print $res[0];

N.D

是我尝试解析以提取我想要的值之一时的结果

关于我使用的 xpath 我已经检查过它与页面源代码的验证......

我哪里做错了?

我解决了!

我的原始代码 "quite" 正确,只是有一个错误。

你必须评论这一行...

//@$dom->loadHTML(json_encode($res[0]));

并用这个替换它

@$dom->loadHTML($res[0]);

一切都会好起来的!