這是一個(gè)簡(jiǎn)單的php加phpquery實(shí)現(xiàn)抓取京東商品分類頁內(nèi)容的簡(jiǎn)易爬蟲。phpquery可以非常簡(jiǎn)單地幫助你抽取想要的html內(nèi)容,phpquery和jquery非常類似,可以說是幾乎一樣;如果你有jquery的基礎(chǔ)的話你可以迅速地上手。
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、運(yùn)行效果
這樣可以抓取京東商品分類的信息了。可以加上數(shù)據(jù)庫,將數(shù)據(jù)保存在數(shù)據(jù)庫中,這樣可以更利于數(shù)據(jù)的保存和操作。雖然這里只是抓取京東商品的分類,如果延伸一下的話還可以抓取商品價(jià)格,好評(píng)差評(píng)等信息。這里就不一一細(xì)說了,具體問題具體解決,完全看需求。如果有需要的話還可以做成萬能的,輸入標(biāo)簽的xpath,然后得到具體的值;這純屬YY,有興趣的可以網(wǎng)上找找資料,實(shí)現(xiàn)的方式應(yīng)該也不少。
PHP編程鄭重聲明:本文版權(quán)歸原作者所有,轉(zhuǎn)載文章僅為傳播更多信息之目的,如作者信息標(biāo)記有誤,請(qǐng)第一時(shí)間聯(lián)系我們修改或刪除,多謝。
新聞熱點(diǎn)
疑難解答
圖片精選