本站的部分文章是在其他平台转载过来的,这里面用到了爬虫技术。
simple_html_dom
simple_html_dom是一款很好用的html Dom解析拓展,对于html内容处理十分强大。
它可以像jQuery一样,通过元素的id,class等标签来定位,很方便的对html元素进行查找选择;同时还提供添加、删除、修改文档树等操作功能。
Laravel5使用simple_html_dom
在Laravel5中可以通过 Composer 直接引入 sunra/php-simple-html-dom-parser 拓展。
sunra/php-simple-html-dom-parser 拓展包地址
php-simple-dom 中文文档
"require": {
"sunra/php-simple-html-dom-parser": "1.5.2"
}
然后在使用文件中直接use使用
use Sunra\PhpSimple\HtmlDomParser;
...
$dom = HtmlDomParser::str_get_html( $str );
or
$dom = HtmlDomParser::file_get_html( $file_name );
$elems = $dom->find($elem_name);
...
Demo
/**
* 爬取某网站文章
*/
public function crawler()
{
//获取html数据转化为对象
$html = HtmlDomParser::file_get_html("https://www.xxx.com");
//获取标签内的内容
$listData=$html->find("div[class='item']");//$listData为数组对象
foreach($listData as $k => $v){
$content_url=$v->find("a[class='content_url']",0)->href;//获取文章地址地址
$addpost['post_title'] = $v->find("a[class='content_url']",0)->title; //标题
$addpost['post_excerpt'] = $v->find("p[class='post_excerpt']",0)->plaintext; //描述
// 打开获取到的文章地址
$html_2 = HtmlDomParser::file_get_html($content_url);
$addpost['post_content'] = $html_2->find("#articleContent",0)->innertext;//内容
$addpost['post_keywords'] = $html_2->find("meta[name='keywords']",0)->content;//关键字
// 保存文章
// ...
$html_2 ->clear();
}
$html->clear();
}