我正在创建一个小型网络应用程序来帮助我管理和分析网站内容,而 cURL 是我最喜欢的新玩具。我已经弄清楚如何提取有关各种元素的信息,如何查找具有特定类的所有元素等,但我遇到了两个问题(见下文)。我希望有一些漂亮的 xpath 答案,但如果我必须诉诸正则表达式,我想那也可以。虽然我不太擅长正则表达式,所以如果你认为这是可行的方法,我会很感激的例子......
相当标准的起点:
$ch = curl_init();
curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$html = curl_exec($ch);
if (!$html) {
$info .= "<br />cURL error number:" .curl_errno($ch);
$info .= "<br />cURL error:" . curl_error($ch);
return $info;
}
$dom = new DOMDocument();
@$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
以及信息的提取,例如:
// iframes
$iframes = $xpath->evaluate("/html/body//iframe");
$info .= '<h3>iframes ('.$iframes->length.'):</h3>';
for ($i = 0; $i < $iframes->length; $i++) {
// get iframe attributes
$iframe = $iframes->item($i);
$framesrc = $iframe->getAttribute("src");
$framewidth = $iframe->getAttribute("width");
$frameheight = $iframe->getAttribute("height");
$framealt = $iframe->getAttribute("alt");
$frameclass = $iframe->getAttribute("class");
$info .= $framesrc.' ('.$framewidth.'x'.$frameheight.'; class="'.$frameclass.'")'.'<br />';
}
疑问/问题:
-
如何提取HTML注释?
我不知道如何识别评论——它们被认为是节点,还是完全是其他东西?
如何获取div的全部内容,包括子节点?因此,如果 div 包含一个图像和几个 href,它会找到这些内容并将其作为 HTML 块全部返回给我。