2017-10-04 89 views
0

我已经搜索并尝试了多种方式来获取此信息,但我不确定它为什么无法找到网页上的大部分信息。使用xpath从网页中刮掉特定文本

页凑: https://m.safeguardproperties.com/

信息需要:以文本所需的苹果(目前为4.4.0)

的XPath PhotoDirect 版本号(我认为):/ HTML /体/ DIV [ 1]/DIV [2]/DIV [1]/DIV [4]/DIV [3] /一个

尝试:

<?php 

$file = "https://m.safeguardproperties.com/"; 
$doc = new DOMDocument(); 
$doc->loadHTMLFile($file); 

$xpath = new DOMXpath($doc); 

$elements = $xpath->query("/html/body/div[1]/div[2]/div[1]/div[4]/div[3]/a"); 

echo "<PRE>"; 

if (!is_null($elements)) { 
    foreach ($elements as $element) { 
     var_dump ($element); 
    echo "<br/>[". $element->nodeName. "]"; 

    $nodes = $element->childNodes; 
    foreach ($nodes as $node) { 
     echo $node->nodeValue. "\n"; 
    } 
    } 
} 

echo "</PRE>"; 

?> 

第二次尝试:

<?PHP 
$file = "https://m.safeguardproperties.com/"; 
$doc = new DOMDocument(); 
$doc->loadHTMLFile($file); 

echo '<pre>'; 

    // trying to find all links in document to see if I can see the correct one 
    $links = []; 
    $arr = $doc->getElementsByTagName("a"); 

    foreach($arr as $item) { 
    $href = $item->getAttribute("href"); 
    $text = trim(preg_replace("/[\r\n]+/", " ", $item->nodeValue)); 
    $links[] = [ 
     'href' => $href, 
     'text' => $text 
    ]; 
    } 

var_dump($links); 
echo '</pre>'; 
?> 
+0

您可以使用$ x()命令行函数在Chrome中验证您的xpath表达式。一旦你有这个工作,把验证的表达式放到你的PHP中。 – Baldy

回答

1

对于那个特定的网站,这些版本是从JSON数据客户端加载的,你不会在基础文档中找到它们。

http://m.safeguardproperties.com/js/photodirect.json

这是位于由原始文档源进行比较来完成的DOM并检查在显影剂控制台网络活动。

$url = 'https://m.safeguardproperties.com/js/photodirect.json'; 
$json = file_get_contents($url); 
$object = json_decode($json); 
echo $object->ios->version; //4.4.0 

请尊重其他网站并缓存您的GET请求。