dongshi2141 2017-10-04 21:55
浏览 110
已采纳

使用xpath从网页刮取特定文本

I've searched and tried multiple ways to get this but I'm not sure why it won't find most of the information on the webpage.

Page to scrape: https://m.safeguardproperties.com/

Info needed: Version number for PhotoDirect for Apple (currently 4.4.0)

Xpath to text needed (I think) : /html/body/div[1]/div[2]/div[1]/div[4]/div[3]/a

Attempts:

<?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. "
";
    }
  }
}

echo "</PRE>";

?>

Second Attempt:

<?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("/[
]+/", " ", $item->nodeValue));
    $links[] = [
      'href' => $href,
      'text' => $text
    ];
  }

var_dump($links);
echo '</pre>';
?>
  • 写回答

1条回答 默认 最新

  • donglin4636 2017-10-04 22:18
    关注

    For that particular website, the versions are being loaded from JSON data client side, you won't find them in the base document.

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

    This was located by comparing the original document source to the finished DOM and inspecting the network activity in the developer console.

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

    Please respect other websites and cache your GET request.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器