【问题标题】:Scraping specific text from a webpage using xpath使用 xpath 从网页中抓取特定文本
【发布时间】:2017-10-05 06:18:36
【问题描述】:

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

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

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

需要文本的Xpath(我认为):/html/body/div[1]/div[2]/div[1]/div[4]/div[3]/a

尝试:

<?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>';
?>

【问题讨论】:

  • 您可以使用 $x() 命令行函数在 Chrome 中验证您的 xpath 表达式。完成该工作后,将经过验证的表达式放入您的 PHP 中。

标签: php html dom xpath extract


【解决方案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 请求。

【讨论】:

    猜你喜欢
    • 2020-06-17
    • 2021-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-06
    • 2018-02-04
    • 2013-11-16
    相关资源
    最近更新 更多