我正在创建一个小型的网络应用程序来帮助我管理和分析我的网站的内容,而cURL是我最喜欢的新玩具。我已经想出了如何提取有关各种元素的信息,如何找到具有某个类的所有元素等,但我陷入了两个问题(见下文)。我希望有一些漂亮的xpath的答案,但如果我不得不诉诸正则表达式,我想没关系。虽然如此,如果你认为这是走的路我不是正则表达式如此之大,我会很感激的例子...如何提取html注释和节点包含的所有html?
非常标准的出发点:
$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 .= "
cURL error number:" .curl_errno($ch);
$info .= "
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 .= '
iframes ('.$iframes->length.'):
';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.'")'.'
';
}
问题/问题:
如何提取HTML注释?
我不知道如何识别评论 - 他们认为是节点,或完全是其他的东西?
如何获取div的全部内容,包括子节点?因此,如果div包含一个图像和一些hrefs,它会找到这些图像并将它们作为HTML块传递给我。
2011-05-18
codebird
+3
不要使用正则表达式提取HTML标记的块,见[正则表达式匹配除了XHTML标签开放自我包含的标签](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags) –
2011-05-18 22:02:19