【问题标题】:How to parse a HTML page that is the POST request result (using curl, JSONPath, Xpath in PHP)?如何解析作为 POST 请求结果的 HTML 页面(在 PHP 中使用 curl、JSONPath、Xpath)?
【发布时间】:2018-06-09 03:16:24
【问题描述】:

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

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

...使用 PHP 提取表格中“ROSSO”、“GIALLO”、“VERDE”和“BIANCO”列下的数字。

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

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

这是我用来使用 curl 发送 POST 请求的 PHP 代码,而不是解析 JSON 响应(使用 Skyscanner JSON Path .. 它在我的代码中运行良好 .. ),尝试使用提取值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;

    ?>

结果如下图

表格是我代码中命令的结果...

print $res[0];

N.D

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

关于我正在使用的 xpath,我已经检查过它正在使用页面源代码进行验证......

我哪里做错了?

【问题讨论】:

    标签: php json curl xpath jsonpath


    【解决方案1】:

    我解决了!

    我的原始代码“完全”正确,除了一个错误。

    你必须评论这一行......

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

    并用这个替换它

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

    一切都会好起来的!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-17
      • 1970-01-01
      • 1970-01-01
      • 2011-03-25
      • 1970-01-01
      • 1970-01-01
      • 2011-11-21
      • 1970-01-01
      相关资源
      最近更新 更多