php使用curl+DomDocument抓取数据

很早之前我们用 正则表达式来匹配网页中的html标签和属性,来抓取数据,现在看来确实有点过时和麻烦了。
现在有了 php DomDocument 对象来处理这些事情了

$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 "
cURL error number:" .curl_errno($ch);
echo "
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");

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

}
?>

你可能感兴趣的:(php使用curl+DomDocument抓取数据)