首页 > php开发 > 几种PHP实现网页抓取的程序代码

几种PHP实现网页抓取的程序代码

网页抓取就像搜索引擎一个可以去自动抓取其它服务器上的内容了,下面我整理的几个php常用做法,大家一起来看看.

抓取某一个网页中的内容,需要对DOM树进行解析,找到指定节点后,再抓取我们需要的内容,过程有点繁琐,LZ总结了几种常用的、易于实现的网页抓取方式,如果熟悉JQuery选择器,这几种框架会相当简单.

一、Ganon

项目地址:http://code.google.com/p/ganon/

文档:http://code.google.com/p/ganon/w/list

测试:抓取我的网站首页所有class属性值是focus的div元素,并且输出class值

<?php 
	 include 'ganon.php'; 
	 $html = file_get_dom('http://www.111cn.net/'); 
	 foreach($html('div[class="focus"]') as $element) { 
	   echo $element->class, "<br>n";  
	 } 
	 

二、phpQuery

项目地址:http://code.google.com/p/phpquery/

文档:https://code.google.com/p/phpquery/wiki/Manual

测试:抓取我网站首页的article标签元素,然后出书其下h2标签的html值

<?php 
	include 'phpQuery/phpQuery.php';  
	phpQuery::newDocumentFile('http://www.phprm.com/');  
	$artlist = pq("article");  
	foreach($artlist as $title){  
	   echo pq($title)->find('h2')->html()."<br/>";  
	}   
	 

三、Simple-Html-Dom

项目地址:http://simplehtmldom.sourceforge.net/

文档:http://simplehtmldom.sourceforge.net/manual.htm

测试:抓取我网站首页的所有链接

<?php 
	include 'simple_html_dom.php'; 
	//使用url和file都可以创建DOM 
	$html = file_get_html('http://www.phprm.com/'); 
	 
	//找到所有图片 
	// foreach($html->find('img') as $element) 
	//        echo $element->src . '<br>'; 
	 
	//找到所有链接 
	foreach($html->find('a') as $element) 
	       echo $element->href . '<br>';  
	

四、Snoopy

项目地址:http://code.google.com/p/phpquery/

文档:http://code.google.com/p/phpquery/wiki/Manual

测试:抓取我的网站首页

<?php 
	include("Snoopy.class.php"); 
	$url = "http://www.phprm.com"; 
	$snoopy = new Snoopy; 
	$snoopy->fetch($url); //获取所有内容 
	 echo $snoopy->results; //显示结果 
	// echo $snoopy->fetchtext ;//获取文本内容(去掉html代码) 
	// echo $snoopy->fetchlinks($url) ;//获取链接 
	// $snoopy->fetchform ;//获取表单  
	 

五、手动编写爬虫

如果编写能力ok,可以手写一个网页爬虫,实现网页抓取,网上有千篇一律的介绍此方法的文章,LZ就不赘述了,有兴趣了解的,可以百度  php 网页抓取.

本文地址:http://www.phprm.com/develop/fs9102.html

转载随意,但请附上文章地址:-)

标签:php网页抓取 php抓取网页

发表留言