快速开发一个PHP电影爬虫

时间:2023-03-09 00:36:30
快速开发一个PHP电影爬虫

今天来做一个PHP电影小爬虫。
我们来利用simple_html_dom的采集数据实例,这是一个PHP的库,上手很容易。
simple_html_dom 可以很好的帮助我们利用php解析html文档。通过这个php封装类可以很方便的解析html文档,对其中的html元素进行操作 (PHP5+以上版本)
下载地址:https://github.com/samacs/simple_html_dom
下面我们以 http://www.paopaotv.com 上的列表页 http://paopaotv.com/tv-type-id-5-pg-1.html 字母模式展现的列表为例,抓取页面上的列表数据,以及内容里面信息

 <?php
include_once 'simple_html_dom.php';
//获取html数据转化为对象
$html = file_get_html('http://paopaotv.com/tv-type-id-5-pg-1.html');
//A-Z的字母列表每条数据是在id=letter-focus 的div内class= letter-focus-item的dl标签内,用find方法查找即为
$listData=$html->find("#letter-focus .letter-focus-item");//$listData为数组对象
foreach($listData as$key=>$eachRowData){
$filmName=$eachRowData->find("dd span",0)->plaintext;//获取影视名称
$filmUrl=$eachRowData->find("dd a",0)->href;//获取dd标签下影视对应的地址
//获取影视的详细信息
$filmInfo=file_get_html("http://paopaotv.com".$filmUrl);
$filmDetail=$filmInfo->find(".info dl");
foreach($filmDetail as $film){
$info=$film->find("dd");
$row=null;
foreach($info as $childInfo){
$row[]=$childInfo->plaintext;
}
$cate[$key][]=join(",",$row);//将影视的信息存放到数组中
}
}

这样通过simple_html_dom,就可以将paopaotv.com影视列表中信息,以及影视的具体信息就抓取到了,之后你可以继续抓取影视详细页面上的视频地址信息,然后将该影视的所有信息都存放到数据库中。
下面是simple_html_dom常用的属性以及方法:

 $html = file_get_html('http://paopaotv.com/tv-type-id-5-pg-1.html');
$e = $html->find("div", 0);
//标签
$e->tag;
//外文本
$e->outertext;
//内文本
$e->innertext;
//纯文本
$e->plaintext;
//子元素
$e->children ( [int $index] );
//父元素
$e->parent ();
//第一个子元素
$e->first_child ();
//最后一个子元素
$e->last_child ();
//后一个兄弟元素
$e->next_sibling ();
//前一个兄弟元素
$e->prev_sibling ();
//标签数组
$ret = $html->find('a');
//第一个a标签
$ret = $html->find('a', 0);

更多用法可以参考官方手册。
是不是很简单呢?有问题欢迎提出来交流

相关文章