php爬虫抓取百度贴吧图片
2013-03-30 15:44
363 查看
最近有从百度贴吧上批量下载图片的需求,即从某一个贴吧下载所有图片。
本来打算用python写的,因为对python不熟悉,试了minidom,HtmlParser等,感觉上不了手,还是使用比较擅长的php语言吧。
以下是源代码:
运行测试:
程序基本上可以满足要求,但是长时间抓取图片时,百度会弹出验证码,此时使用猫重新拨号即可更换IP继续抓取图片。
(仅供学习参考,请勿用来做非法的事情。)
本来打算用python写的,因为对python不熟悉,试了minidom,HtmlParser等,感觉上不了手,还是使用比较擅长的php语言吧。
以下是源代码:
<?php //运行时间 @set_time_limit(60); //贴吧名称 $tbname = "%CD%BC%C6%AC"; //抓取类型 0-按照帖子顺序 1-按照贴图顺序 $type = 0; //列表页url $listurltpl = "http://tieba.baidu.com/f?kw=%s".($type?"&tp=1":"&pn="); //图册页url $galleryurltpl = "http://tieba.baidu.com/photo/bw/picture/guide?kw=%s&tid=%s&next=9999"; //图片url $imageurltpl = "http://imgsrc.baidu.com/forum/pic/item/%s.jpg"; //本地的目录 $savepath = "h:/images/"; //帖子子文件夹 $filedirtpl = $savepath."%s/"; //图片文件 $filenametpl = $savepath."%s/%s.jpg"; $listurl = sprintf($listurltpl,$tbname); //抓取起始点 $pn = 0; while(1) { if (!$type) $listurl .= $pn; //得到列表页源代码 $listhtml = file_get_contents($listurl); //匹配出帖子id if($type) preg_match_all('/<div class=\"aep_wrapper\" id=\"pic_item_(\d+)\" tid=\"\d+\">/',$listhtml,$m1); else preg_match_all('/<ul class=\"threadlist_media j_threadlist_media\" id=\"fm(\d+)\"/',$listhtml,$m1); //得到帖子id列表 $tidlist = $m1[1]; echo "Fetching ... <br /> \r\n"; foreach($tidlist as $tid) { echo "--Gallery $tid <br /> \r\n"; $galleryurl = sprintf($galleryurltpl,$tbname,$tid); //得到帖子图册的源代码 $galleryhtml = file_get_contents($galleryurl); //匹配出图片id preg_match_all('/\{\"original\":\{\"id\":\"(\w+)\"/',$galleryhtml,$m2); //得到图片id列表 $pidlist = $m2[1]; foreach($pidlist as $pid) { echo "----Picture {$tid}/{$pid}.jpg "; $filedir = sprintf($filedirtpl,$tid); $filename = sprintf($filenametpl,$tid,$pid); //文件是否存在 if(!is_file($filename)) { $imageurl = sprintf($imageurltpl,$pid); //下载图片 $imagebin = file_get_contents($imageurl); //目录是否存在 if(!is_dir($filedir)) mkdir($filedir); //保存图片 file_put_contents($filename,$imagebin); $rnd = rand(2000,5000); echo "Downloaded! "; //延时休息 sleep(1.0*$rnd/1000); echo "Sleep $rnd us <br />\r\n"; } else echo "Existed! <br />\r\n"; } } //翻到下一页 if (!$type) $pn += 50; }
运行测试:
程序基本上可以满足要求,但是长时间抓取图片时,百度会弹出验证码,此时使用猫重新拨号即可更换IP继续抓取图片。
(仅供学习参考,请勿用来做非法的事情。)
相关文章推荐
- 利用爬虫抓取百度贴吧的图片
- Python爬虫学习笔记二:百度贴吧网页图片抓取
- Python爬虫--抓取百度贴吧图片
- Python爬虫实战(1)——百度贴吧抓取帖子并保存内容和图片
- 简单的PHP爬虫抓取百度贴吧用户数据
- python爬虫 -- 抓取网页中链接的静态图片
- php远程抓取网站图片并保存的代码
- python抓取网页图片示例(python爬虫)
- 爬虫实践---抓取百度贴吧
- PHP通过CURL实现定时任务的图片抓取功能示例
- 使用简易Python爬虫下载百度贴吧图片
- 【python爬虫】百度贴吧帖子图片批量保存爬虫
- php远程抓取网站图片并保存
- 爬虫抓取百度贴吧帖子内容
- 网页抓取:PHP实现网页爬虫方式小结
- PHP抓取百度贴吧邮箱v1.0
- php如何抓取远程图片到七牛
- 爬虫抓取百度贴吧帖子标题及作者
- PHP抓取图片函数
- 简单的抓取淘宝关键字信息、图片的Python爬虫|Python3中级玩家:淘宝天猫商品搜索爬虫自动化工具(第二篇)