昨天面試萌寶的php實(shí)習(xí)言询,給了我一個(gè)爬蟲的題目尔觉,瞬間懵逼凉袱,我的天,從來沒接觸過爬蟲啊侦铜。于是簡單的了解了下专甩,決定用html-parse來解析html_dom,因?yàn)檎嫘膶?duì)正則表達(dá)式感到害怕钉稍。
然而最后還是被pass了涤躲,說小公司,我的能力達(dá)不到...建議我去大公司嫁盲。篓叶。烈掠。果然還是大公司比較好進(jìn)是吧羞秤?
public function start(){
//獲取鏈接數(shù)組
$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');
// 獲取基礎(chǔ)信息
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(導(dǎo)演,主演左敌,編勸啊) 測試階段被墻了
// }
}
}
//將json寫入文件
file_put_contents("/Users/z/Code/test.txt",json_encode($movies));
}
// 設(shè)置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條數(shù)據(jù)的鏈接數(shù)組
$this->linksArray = array_map(function ($linksuffix){
return self::URL.$linksuffix->getAttr('href');
},$linksuffixs);
array_pop($this->linksArray);
array_unshift($this->linksArray,self::URL);
}
//根據(jù)url,獲取dom對(duì)象
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;
}
}
}
` ` `