這是一個簡單的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,有興趣的可以網上找找資料,實現的方式應該也不少。