2019-08-30 18:07:52
围观(4765)
最近因为工作需要,另外自己也对爬虫比较感兴趣,但无奈于不会 Python 也懒得学。
所以用 PHP 简单的爬了一下某招聘网站的职位分类和公众号的文章。
使用了第三方的类:PHP Simple HTML DOM Parser. 官网:https://simplehtmldom.sourceforge.io/
稍微改一下就可以用在框架上了,经过博主修改后的类下载地址:https://pan.baidu.com/s/1pYmLJ_r1XicuKX63XgkZKQ 提取码:r12h
用在 Laravel 框架时,需要在 composer.json 定义一下。如:
"autoload": {
"psr-4": {
"App": "app/"
},
"classmap": [
"database/seeds",
"database/factories",
"extend/spiders" //这里添加一行代码 引入类
]
},然后就可以定义路由 在控制器里面引入该类写爬取内容的方法了。
比如简单爬取某招聘网的职业分类:
public function index()
{
$html = (new Spiders)->file_get_html('https://zhipin.com');
foreach ($html->find('div.menu-sub') as $top_key => $top_value) {
//顶级分类
$top_title = $top_value->find('p.menu-article', 0)->plaintext;
echo '<br>-----------------------------<br>|- ' . $top_title . '<br>';
//可以将 $top_title 入库,上级ID为0 并取出ID...
//二级分类
foreach ($top_value->find('ul li h4') as $second_key => $second_value) {
echo ' |-- ' . $second_value->plaintext . '<br>';
//可以将 $second_value->plaintext 入库,上级ID为顶级分类取出的ID...
//三级分类
foreach ($second_value->parent()->find('div.text a') as $three_key => $three_value) {
echo ' |--- ' . $three_value->plaintext . '<br>';
//可以将 $three_value->plaintext 入库,上级ID为二级分类取出的ID...
}
}
}
}最后呈现的效果是这样的:

还可以爬公众号文章的内容:
public function wechat()
{
$html = (new Spiders)->file_get_html('公众号文章地址');
$content = $html->find('body');
//获取所有图片
foreach($html->find('img[data-src]') as $img){
$img_path = $img->{'data-src'};
if(empty($img_path)){
continue;
}
//获取后缀名
$extension = mb_substr($img_path, mb_strrpos($img_path, '=') + 1);
//保存图片 因为有防盗链
$file_name = '/img/' . uniqid() . rand(1000, 9999) . '.'. $extension;
file_put_contents(public_path() . $file_name, file_get_contents($img_path));
//修改img标签
$img->src = $file_name;
}
//保存到public目录下的test.html
$html->save(public_path() . '/test.html');
}简单几行代码就爬下了公众号文章页的整个页面,如果只需要 Body 里面的内容把HTML都去掉的话也是可以的。还可以根据需要处理成更精细的数据保存到数据库。
这两个爬虫都很简单,可以当成练手的玩具玩玩。
更高级的爬虫还涉及到了更换IP/使用IP代理及伪装UA之类的。
还发现了一个国人开发的 PHP 爬虫框架:http://www.querylist.cc/ 应该还挺有意思的。
本文地址 : bubaijun.com/page.php?id=134
版权声明 : 未经允许禁止转载!
上一篇文章: 使用原生PHP写一个敏感词检测过滤接口
下一篇文章: 快速给博客加上“历史上的今天”