天天看点

php 网页数据抓取 简单实例

最近想学习一下数据抓取方面的知识,花了一个中午时间边学便实验,很快就把代码写出来了,实例写得比较简单,学习思路为主。需要注意的是,在目标网页上获取的数据如果有中文的话,可能会导致乱码的情况,这时可以用 iconv ( "UTF-8", "ISO-8859-1//TRANSLIT", string ) 这个函数进行编码,第一个参数是传入的编码,第二个参数是输出的编码,第三个参数是需要编码的字符串。另外,对xpath的知识不熟悉的话可以去w3cshool学习一下,因为这个比较重要。

<?php

$uri = array (

4 => 'http://www.kuitao8.com/search/index/search/yii/page/4',

3 => 'http://www.kuitao8.com/search/index/search/yii/page/3',

2 => 'http://www.kuitao8.com/search/index/search/yii/page/2',

1 => 'http://www.kuitao8.com/search/index?search=yii'

);

$result = array ();

// 创建一个DOM对象

$dom = new DOMDocument ();

// 遍历uri数组,解析DOM数据

foreach ( $uri as $url ) {

// 读取html文件

$dom->loadHTMLFile ( $url );

// 转换成DOM对象

$xml = simplexml_import_dom ( $dom );

// 利用xpath进行找数据

$xpath = $xml->xpath ( '/html/body//a[@class="view_more"]' );

// 遍历找到的数据,并储存在新的$result数组中

foreach ( $xpath as $object ) {

// 指向DOM对象的 属性值

$att = $object->attributes ();

// 连接uri

$a .= '<a href="http://www.kuitao8.com/';

$a .= iconv ( " target="_blank" rel="external nofollow" UTF-8", "ISO-8859-1//TRANSLIT", $att->href );

$a .= '">';

$a .= iconv ( "UTF-8", "ISO-8859-1//TRANSLIT", $att->title );

$a .= '</a><br>';

// 把连接储存到新数组

$result [] = $a;

// 重置,

$a = null;

}

// 释放资源 

$xml = null;

$xpath = null;

}

// 打印新数组

print_r ( $result );

?>