PHP数据采集之使用CURL、DOMDocument和DOMXPath

这三个组件有各自独特的功能:

  • CURL能够抓取下载HTML,能模拟登陆,伪装客户端等
  • DOMDocument将下载的HTML加载成DOM
  • DOMXPath使用XPath语法进行数据的定位和采集

下面是一个具体的例子代码,抓取了本博客www.crazyant.net首页所有的超链接:

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<?php
$target_url = "http://www.crazyant.net";
$ch = curl_init();

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) {
	echo "<br />cURL error number:" .curl_errno($ch);
	echo "<br />cURL error:" . curl_error($ch);
	exit;
}
//创建一个DomDocument对象,用于处理一个HTML
$dom = new DOMDocument();
//从一个字符串加载HTML
@$dom->loadHTML($html);
//使该HTML规范化
$dom->normalize();

//用DOMXpath加载DOM,用于查询
$xpath = new DOMXPath($dom);
#获取所有的a标签的地址
$hrefs = $xpath->evaluate("/html/body//a//@href");

for ($i = 0; $i < $hrefs->length; $i++) {
	$href = $hrefs->item($i);
	$linktext = $href->nodeValue;
	echo $linktext;
	echo "<BR>";

}
?>

要注意点,DOMNode 类并没有getAttribute方法,所以无法根据a得到直接的属性值,这时可以用正则匹配解决,网上看到很多人直接在DOMNode 上使用了getAttribute方法竟然通过,实在是匪夷所思,如果有更好的解释,请您给我说一说,我很渴望知道怎样直接从Xpath的返回直接得到属性值。

你可能感兴趣的:(document)