【发布时间】: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