使用PHP ad xpath刮擦HTML页面:使用绝对路径的替代方法

时间:2017-12-03 17:00:10

标签: php xpath web-scraping

我正在抓取这个网页......

https://www.sanita.puglia.it/monitorpo/aslfg/monitorps-web/monitorps/monitorPSperASL.do?codNazionale=160115

enter image description here

....使用PHP和XPath在名为&#34的表格下的绿色框中获取值 10 ; PO G. TATARELLA-CERIGNOLA &# 34。

(注意:如果您尝试浏览它,您可以在该页面中看到不同的值...它并不重要......它会改变它的恐怖......)

我使用此PHP代码示例来打印值...

<?php
    ini_set('display_errors', 'On');
    error_reporting(E_ALL);

    $url = 'https://www.sanita.puglia.it/monitorpo/aslfg/monitorps-web/monitorps/monitorPSperASL.do?codNazionale=160115';

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


    //#Set CURL parameters: pay attention to the PROXY config !!!!
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
    curl_setopt($ch, CURLOPT_PROXY, '');
    $data = curl_exec($ch);
    curl_close($ch);

    $dom = new DOMDocument();
    @$dom->loadHTML($data);

    $xpath = new DOMXPath($dom);

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

    print $theValue;
?>

一切正常。

我是一个使用XPath的新手:我想避免使用像

这样的绝对路径
/html/body/div[4]/table/tbody/tr[2]/td[4]/div

但要使用类似

的内容
'//*[div="cRiga3 boxtriageS"]'

(注意:我知道它不起作用,但它只能解释我......)

针对此案例的任何建议或示例?

提前谢谢

编辑:这个问题完全不同尊重Extract string in HTML page using scraping in PHP ad xpath:在那个问题中我的原始代码没有工作......现在我已修复它并且它有效。我现在的问题是如何改进它试图在我的XPath中使用更紧凑的形式并且不使用绝对路径

0 个答案:

没有答案