laravel Htmldom拓展包,laravel爬虫中的html代码解析神器
Song •
3999 次浏览 •
0个评论 •
2017年12月26日
在我们开发和编写爬虫的过程中,常常需要在网页中提取关键字,提取我们需要的内容,python
中大家都是用beautifulsoup
,简直是神器,有了它我们可以快速的提取到网页中我们需要的内容,免去我们慢慢的编写正则表达式;其实,在PHP
中,也有simple_html_dom
能帮助我们快速提取网页内容,在laravel
中也有这样的拓展包Htmldom
,下面我们来看一下怎么使用吧:
一、laravel安装htmldom
composer require yangqi/htmldom
2、等待下载安装完成,需要在config/app.php中注册服务提供者同时注册下相应门面:
providers => [
//........
Yangqi\Htmldom\HtmldomServiceProvider,
],
aliases => [
//..........
Htmldom => Yangqi\Htmldom\Htmldom,
],
三、laravel中htmldom的使用
接下来我门使用一下,其他深入的用法可以参考simplehtmldom用法详解。因为这个拓展没有使用文档,直接看simple_html_dom
就可以了
use Htmldom;
$html = new Htmldom(http://www.baidu.com);
// 提取全部的图片src
foreach($html->find(img) as $element)
echo $element->src . <br>;
// 提取全部的连接
foreach($html->find(a) as $element)
echo $element->href . <br>;
四、拓展使用
好的,上面我们已经讲了很多的用法,下面我们来进行拓展一下,让这个拓展更加适合我们使用,一如我们网站宣传的,复杂的业务逻辑写在Servces
中,下面我根据我的业务逻辑总结了一个使用,这里我做了很多删减,因为我是拿来做爬虫的,所以真的是太多了,这里一种是直接给url
,获取指定内容的,一种是给代码,获取指定内容的,不然朋友们看文档完全蒙蔽,因为没有文档
<?php
namespace App\Services;
use Htmldom;
class HtmldomService
{
/**
* 主要运用PHP Simple HTML DOM Parser Manual
* 此处只封装了常用方法
* 更多方法请参照http://simplehtmldom.sourceforge.net/manual.htm
* 使用方法(获取官网的token):HtmldomService::SimpleGivenHtml(,input,name,_token,value,all);
*/
/**
* 获取页面全部内容,
* sort = 详情:比如plaintext(纯文本)等
*/
public static function SimpleAllHtml($url,$sort)
{
$html = new Htmldom($url);
$result=$html->$sort;
return $result;
}
/**
* 获取页面全部标签,
* url=网站连接,
* dom = 标签:比如a.img等,
* sort = 详情:比如src,href,plaintext,class等
*/
public static function SimpleSingleHtml($url,$dom,$sort)
{
$html = new Htmldom($url);
$result=[];
foreach($html->find($dom) as $element)
$result[]=$element->$sort;
return $result;
}
/**
* 获取页面全部内容,
* sort = 详情:比如plaintext等
*/
public static function strSimpleAllHtml($str,$sort)
{
$htmldom = new Htmldom();
$html = $htmldom->load($str);
$result=$html->$sort;
return $result;
}
/**
* 获取页面全部标签,
* str = 传递过来的为html代码
* dom = 标签:比如a.img等,
* sort = 详情:比如src,href,plaintext,class等
*/
public static function strSimpleSingleHtml($str,$dom,$sort)
{
$htmldom = new Htmldom();
$html = $htmldom->load($str);
$result=[];
foreach($html->find($dom) as $element)
$result[]=$element->$sort;
return $result;
}
}
常见问题
1、输出连接×
被替换成x
当url
中包含×
字段时就会被html
直接解析成x
,你直接使用即可,不用echo
输出
更多相关好文
-
laravel中distinct()的使用方法与去重 2017-09-11
-
Laravel将view缓存为静态html,laravel页面静态缓存 2021-10-09
-
[ laravel爬虫实战--基础篇 ] guzzle描述与安装 2017-11-01
-
[ 配置教程 ] 在ubuntu16.04中部署LNMP环境(php7+maridb且开启maridb远程以及nginx多域名访问 )并配置laravel环境 2017-07-18
-
mysql如何给运营人员添加只有查询权限的账号 2024-12-02
热门文章
-
mysql如何给运营人员添加只有查询权限的账号 2024-12-02
-
Mac 安装mysql并且配置密码 2024-11-20
-
阿里云不同账号(跨账号)ECS服务器同地域如何实现免费内网互通? 2024-11-12
-
electron安装使用better-sqlite3并解决NODE_MODULE_VERSION xxx. This version of Node.js requires 2024-11-06
-
Zerotier+Moon+Nginx实现内网穿透搭建网站 2024-08-23
花生壳绑定ubuntu服务器?