使用 xpath 从网页中抓取特定文本

Scraping specific text from a webpage using xpath

我已经搜索并尝试了多种方法来获取此信息,但我不确定为什么它找不到网页上的大部分信息。

要抓取的页面: https://m.safeguardproperties.com/

需要的信息: PhotoDirect for Apple 的版本号(当前为 4.4.0)

需要文本的 Xpath(我认为):/html/body/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>';
?>

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

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

这是通过将原始文档源与完成的 DOM 进行比较并在开发人员控制台中检查网络 activity 来找到的。

$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 请求。