这是一个简单的php加phpquery实现抓取京东商品分类页内容的简易爬虫。phpquery可以非常简单地帮助你抽取想要的html内容,phpquery和jquery非常类似,可以说是几乎一样;如果你有jquery的基础的话你可以迅速地上手。
1、下载phpquery并置于web根目录下的phpQuery文件夹
phpquery下载:https://code.google.com/p/phpquery/downloads/list
phpquery教程可在这里查看:https://code.google.com/p/phpquery/
2、抓取程序
<?php /* * Created on 2015-1-29 * * To change the template for this generated file go to * Window - Preferences - PHPeclipse - PHP - Code Templates */ header("Content-type:text/html; charset=utf-8"); function getPage( $url ) { $cnt = file_get_contents($url); return mb_convert_encoding($cnt ,"UTF-8","GBK"); } include \'phpQuery/phpQuery.php\'; $url = \'http://www.jd.com/allSort.aspx\'; $page = getPage($url); //phpQuery::newDocumentHTML($page); phpQuery::newDocumentFile($url); $firstCate = pq(\'#allsort .m\'); $id = 0; foreach($firstCate as $first){ $id ++; $topcate = pq($first)->find(".mt a"); //echo "**************************" . $topcate->text() . "**************************************</br>"; echo $id . "#"; foreach($topcate as $top){ echo pq($top)->text() . "#" . "< a href=\'" .pq($top)->attr("href") . "\' target=\'_blank\'>" . pq($top)->text() ."< /a>、"; } echo "#0#1</br>"; $companies = pq($first)->find(".mc dl"); $parent_id = $id; foreach($companies as $company) { $id++; $sparent_id = $id; echo " " . $id . "#" .pq($company)->find(\'dt\')->text() . "#" . "< a href=\'" . pq($company)->find(\'dt a\')->attr("href") . "\' target=\'_blank\'>" . pq($company)->find(\'dt\')->text() ."< /a>#" . $parent_id ."#2<br>"; $cate = pq($company)->find(\'dd em a\'); foreach($cate as $detail) { $id++; echo " " . $id . "#" .pq($detail)->text() . "#" . "< a href=\'". pq($detail)->attr("href") . "\' target=\'_blank\'>" . pq($detail)->text() ."< /a>#" . $sparent_id . "#3<br>"; } } } ?>
3、运行效果
这样可以抓取京东商品分类的信息了。可以加上数据库,将数据保存在数据库中,这样可以更利于数据的保存和操作。虽然这里只是抓取京东商品的分类,如果延伸一下的话还可以抓取商品价格,好评差评等信息。这里就不一一细说了,具体问题具体解决,完全看需求。如果有需要的话还可以做成万能的,输入标签的xpath,然后得到具体的值;这纯属YY,有兴趣的可以网上找找资料,实现的方式应该也不少。