• 技术文章 >php框架 >Laravel

    在laravel中使用simple_html_dom爬取显示整本小说

    L先生L先生2020-05-07 14:51:57原创1313
    如在程序员还看带广告的小说中所述,很多小说网站基本都有特别烦人的广告,要么在整体div添加链接,误触就会跳转到一些网站甚至是死循环,某些手机app也是广告很多,本文就将其应用到laravel框架,最好先了解上一篇,随后自行部署就可以了。

    一、在laravel引入第三方类

    1.在项目根目录下app目录中新建一个文件夹命名为Lib(自定义名称)

    2.如果引入第三方库多的话可以在Lib下再新建几个目录分类,由于只引入了一个类,这里没有新建文件夹。(根据引入类的多少自己定义)

    将simple_html_dom.php复制到Lib下

    3.找到项目根目录下的composer.json文件,将第三方类的路劲写入autoload下的classmap中,这样才能自动加载

    "autoload": {
    "classmap": [
    "database/seeds",
    "database/factories",
    "app/Lib/simple_html_dom.php"
    ]
    },

    4.在cmd控制台中切换到项目根目录,执行命令:

    composer dumpautoload

    5.在控制器中use这个类即可

    use simple_html_dom;

    $html = new simple_html_dom(); 使用

    二、创建路由

    Route::get('/novel_list','index\Spnovel@index');

    三、创建控制器Spnovel.php

    <?php
    namespace App\Http\Controllers\index;
    use simple_html_dom;
    use Illuminate\Http\Request;
    use App\Http\Controllers\Controller;
    class Spnovel extends Controller
    {
    	public function index(){
    		$url = "https://www.7kzw.com/85/85445/";
    		$list_html = mySpClass::getCurl($url);
    		$data['List'] = self::getList($list_html);
    		return view('index.spnovel.index',$data);
    	}
    	private static function getList($list_html){
    		$html = new simple_html_dom();
    		@$html->load($list_html);
    		$list = $html->find('#list dd a');
    		foreach ($list as $k=>$v) {
    			$arr1=$arr2=[];
    			$p1 = '/<a .*?>(.*?)<\/a>/i';
    			$p2 = '/<a .*? href="(.*?)">.*?<\/a>/i';
    			preg_match($p1,$v->outertext,$arr1);
    			preg_match($p2,$v->outertext,$arr2);
    			$content[$k][0]=$arr1[1];
    			$content[$k][1]=$arr2[1];
    		}
    		array_splice($content,0,12); 
    		return $content;
    	}
    }
    class mySpClass{
    	// 向服务器发送最简单的get请求
    	public static function getCurl($url,$header=null){
    		// 1.初始化
    		$ch = curl_init($url);   //请求的地址
    		// 2.设置选项
    		curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);//获取的信息以字符串返回,而不是直接输出(必须) 
    		curl_setopt($ch,CURLOPT_TIMEOUT,10);//超时时间(必须)
    		curl_setopt($ch, CURLOPT_HEADER,0);// 	启用时会将头文件的信息作为数据流输出。 
    		//参数为1表示输出信息头,为0表示不输出
    		curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false); //不验证证书
    		curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false); //不验证证书
    		if(!empty($header)){
    			curl_setopt($ch,CURLOPT_HTTPHEADER,$header);//设置头信息
    		}else{
    			$_head = [
    			'User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:70.0) Gecko/20100101 Firefox/70.0'
    			]; 
    			curl_setopt($ch,CURLOPT_HTTPHEADER,$_head);
    		}
    		// 3.执行
    		$res = curl_exec($ch);
    		// 4.关闭
    		curl_close($ch);
    		return $res;
    	}
    }

    以上代码的解释:首先要对laravel框架了解,对php类要有所了解

    访问了以上路由,运行的是Spnovel.php控制器中的index方法,$url是某一本小说的章节列表的地址,将其作为参数运行自定义类mySpClass中的getcurl方法,返回这个页面的html文档字符串。运行此类中的getList方法,参数是需要解析的html字符串。将这个方法私有化,使用simple_html_dom解析,配置正则提取出每章的url地址和章节名称。并返回这个数组,通过return view('index.spnovel.index',$data);将打开index/spnovel/index.blade.php,请看index.blade.php

    四、创建视图index.blade.php

    <!DOCTYPE html>
    <html>
    <head>
    	<title>爬取的小说列表</title>
    	<style type="text/css">
    	body{padding:0px;margin:0px;}
    	#lists{width:100%;padding:30px 50px;box-sizing:border-box;}
    	ul{margin:0;padding: 0;overflow:hidden;}
    	ul li{list-style:none;display:inline-block;float:left;width:25%;color:#444;}
    	ul li:hover{color:#777;cursor: pointer;}
    	img {z-index:-1;width:100%;height:100%;position:fixed;}
    	</style>
    </head>
    <body>
    	<img src="/static/img/index/novelbg.jpg">
    	<div id="lists">
    		<ul>
    			@foreach($List as $item)
    			<li>
    			<a href="/novel_con{{$item[1]}}">{{$item[0]}}</a>
    			</li>
    			@endforeach
    		</ul>		
    	</div>
    </body>
    </html>

    以上代码的解释:css就简单的写到这里,img是作为背景图片的。ul里面循环li,{{$item[1]}}是获得的地址参数,{{$item[0]}}是获得的章节名称。看一下数组和最后的效果。

    QQ截图20200507121544.png

    五、运行

    QQ截图20200507121443.png

    接下来就是每一章节的内容了

    先看路由

    Route::get('/novel_con/{a}/{b}/{c}','index\Spnovel@get_nContent');

    这与每一章的url参数相对应,比如某一章的参数为:novel_con/85/85445/27248645.html

    get_nContent方法

    public function get_nContent(Request $req){
    		$url1 = $req->a.'/'.$req->b.'/'.$req->c;
    		$url = "https://www.7kzw.com/".$url1;
    		$res = mySpClass::getCurl($url);//获得
    		// 开始解析
    		$data['artic']= self::getContent($res);
    		$next = (int)$req->c;
    		$next = $next+1;
    		$data['artic']['next']="/novel_con/".$req->a.'/'.$req->b.'/'.$next.'.html';
    		return view('index.spnovel.ncontent',$data);
    	}
    private static function getContent($get_html){
    		$html = new simple_html_dom();
    		@$html->load($get_html);
    		$h1 = $html->find('.bookname h1');
    		foreach ($h1 as $k=>$v) {
    			$artic['title'] = $v->innertext;
    		}
    		// 查找小说的具体内容
    		$divs = $html->find('#content');
    		foreach ($divs as $k=>$v) {
    			$content = $v->innertext;
    		}
    		// 正则替换去除多余部分
    		$pattern = "/(<p>.*?<\/p>)|(<div .*?>.*?<\/div>)/";
    		$artic['content'] = preg_replace($pattern,'',$content);
    		return $artic;
    	}

    解释:$req->a,$req->b,$req->c,分别是三个参数,然后将其合并为一个完整的请求某一章的地址,然后还是通过mySpClass::getCurl获得某一章的html字符串。然后使用本类中的getContent解析这个页面,先看解析方法,和上篇文章一章解析出章节的标题和内容,写到数组中,并且去掉了多余的文字广告部分。$next则是存放的下一章的地址,用于在章节详情页面跳转。

    视图ncontent.blade.php

    <!DOCTYPE html>
    <html>
    <head>
    	<title>{{$artic['title']}}</title>
    	<style type="text/css">
    	h2{text-align:center;padding-top:30px;}
    	div{margin:20px 50px;font-size:20px;}
    	img {z-index:-1;width:100%;height:100%;position:fixed;}
    	.next {position:fixed;right:10px;bottom:20px;background:coral;border-radius:3px;padding:4px;}
    	.next:hover{color:#fff;}
    	</style>
    </head>
    <body>
    	<img src="/static/img/index/novelbg.jpg">
    	<h2>{{$artic['title']}}</h2>
    	<a href="{{$artic['next']}}" class="next">下一章</a>
    	<div>
    		{!!$artic['content']!!}
    	</div>
    </body>
    </html>

    解释:因为只有当前一篇所以不需要循环,{{$artic['title']}}就是标题,也可以写到title中。{!!$artic['content']!!}的写法就是不需要转义文章的内容,否则就会有很多其他字符了,如<br>等。下一章的按钮的地址直接就用传递过来的即可,position:fixed固定定位按钮,随时可以下一章。

    运行

    QQ截图20200507123249.png

    总结:本文最重要的环节就是引入第三方类,能够应用他,还有就是laravel的基础,比较习惯使用控制器视图这种方式,带模型的方式还请自行编写验证。

    就对一本小说来说这就足够了,当然我们可以扩充,将整站的小说列表写出来,继续传合适的参数就更加完美了。

    以上就是在laravel中使用simple_html_dom爬取显示整本小说的详细内容,更多请关注php中文网其它相关文章!

    声明:本文原创发布php中文网,转载请注明出处,感谢您的尊重!如有疑问,请联系admin@php.cn处理
    专题推荐:laravel
    上一篇:如何在大型 Laravel 项目中组织你的路由 下一篇:Laravel 7 扩展开发教程
    大前端线上培训班

    相关文章推荐

    • 推荐10个优质的Laravel扩展• 分享几个 Laravel 7 中很酷的 Blade 组件• Laravel 之添加图片水印• 如何在大型 Laravel 项目中组织你的路由

    全部评论我要评论

  • 取消发布评论发送
  • 1/1

    PHP中文网