昨天面试萌宝的php实习,给了我一个爬虫的题目,瞬间懵逼,我的天,从来没接触过爬虫啊。于是简单的了解了下,决定用html-parse来解析html_dom,因为真心对正则表达式感到害怕。
然而最后还是被pass了,说小公司,我的能力达不到...建议我去大公司。。。果然还是大公司比较好进是吧?
public function start(){
//获取链接数组
$this->setLinksArray();
$movies = [];
foreach($this->linksArray as $link){
$html_dom = $this->getContentByFilegetContent($link);
// 找出items
$ol = $html_dom->find('ol.grid_view',0);
$items = $ol->find('li');
// 获取基础信息
foreach ($items as $item){
$em = $item->find('em',0)->getPlainText();
$title = $item->find('span.title',0)->getPlainText();
$img = $item->find('img',0)->getAttr('src');
$inq = $item->find('span.inq',0);
if($inq == false){
$inq = '';
}else{
$inq=$inq->getPlainText();
}
$rating_num = $item->find('span.rating_num',0)->getPlainText();
$ob = [$em => [
'title'=>$title,
'img'=>$img,
'inq'=>$inq,
'rateing_num'=>$rating_num
]];
array_push($movies,$ob);
// 获取更多信息
// $moreUrl = $item->find('div.hd',0)->find('a',0)->getAttr('href');
// if($this->isUrlValid($moreUrl)){
// echo $moreUrl;
// $moreInfo_dom = $this->getContentByFilegetContent($item->find('div.hd',0)->find('a',0)->getAttr('href'));
// $info_dom = $moreInfo_dom->find('info',0);
// $director = $info_dom->find('span',0)->find('a',0)->getPlainText();
// $bianju = $info_dom->find('span',1)->find('a',0)->getPlainText();
// // 获取moreInfo(导演,主演,编剧) 测试阶段被墙了
// }
}
}
//将json写入文件
file_put_contents("/Users/z/Code/test.txt",json_encode($movies));
}
// 设置linksArray
public function setLinksArray(){
$html_dom = $this->getContentByFilegetContent(self:::URL);
//找出翻页div
$div_paginator = $html_dom->find('div.paginator',0);
$linksuffixs = $div_paginator->find('a');
//250条数据的链接数组
$this->linksArray = array_map(function ($linksuffix){
return self::URL.$linksuffix->getAttr('href');
},$linksuffixs);
array_pop($this->linksArray);
array_unshift($this->linksArray,self::URL);
}
//根据url,获取dom对象
public function getContentByFilegetContent($url){
$content = file_get_contents($url);
$html_dom = new \HtmlParser\ParserDom($content);
return $html_dom;
}
//curl 请求
header("Content-type:text/html;charset=utf-8");
function GetCurl($url){
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_NOBODY,true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION,true);
curl_setopt($ch, CURLOPT_AUTOREFERER,true);
curl_setopt($ch, CURLOPT_TIMEOUT,30);
$rtn = curl_exec($ch);
curl_exec($ch);
return $rtn;
}// 判断url是否有效
public function isUrlValid($url){
$resp = $this->GetCurl($url);
if(strpos($resp,'404 Not Found')==true) {
return false;
}else{
return true;
}
}
}
` ` `