Fork me on GitHub

php+phpquery简易爬虫抓取京东商品分类

  这是一个简单的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 "&nbsp;&nbsp;" . $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 "&nbsp;&nbsp;&nbsp;&nbsp;" .  $id . "#" .pq($detail)->text() . "#" . "< a href='". pq($detail)->attr("href") . "' target='_blank'>" . pq($detail)->text() ."< /a>#" . $sparent_id . "#3<br>"; 
       }
       
    }  
}


?>
复制代码

  3、运行效果

  这样可以抓取京东商品分类的信息了。可以加上数据库,将数据保存在数据库中,这样可以更利于数据的保存和操作。虽然这里只是抓取京东商品的分类,如果延伸一下的话还可以抓取商品价格,好评差评等信息。这里就不一一细说了,具体问题具体解决,完全看需求。如果有需要的话还可以做成万能的,输入标签的xpath,然后得到具体的值;这纯属YY,有兴趣的可以网上找找资料,实现的方式应该也不少。

 

posted @   秋楓  阅读(5596)  评论(1编辑  收藏  举报
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
点击右上角即可分享
微信分享提示