首页 > 开发 > PHP > 正文

php实现简单爬虫的开发

2024-05-04 22:31:36
字体:
来源:转载
供稿:网友

有时候因为工作、自身的需求,我们都会去浏览不同网站去获取我们需要的数据,于是爬虫应运而生,下面是我在开发一个简单爬虫的经过与遇到的问题。

    开发一个爬虫,首先你要知道你的这个爬虫是要用来做什么的。我是要用来去不同网站找特定关键字的文章,并获取它的链接,以便我快速阅读。

    按照个人习惯,我首先要写一个界面,理清下思路。

    1、去不同网站。那么我们需要一个url输入框。
    2、找特定关键字的文章。那么我们需要一个文章标题输入框。
    3、获取文章链接。那么我们需要一个搜索结果的显示容器。

<div class="jumbotron" id="mainJumbotron"> <div class="panel panel-default">   <div class="panel-heading">文章URL抓取</div>   <div class="panel-body">   <div class="form-group">    <label for="article_title">文章标题</label>    <input type="text" class="form-control" id="article_title" placeholder="文章标题">   </div>   <div class="form-group">    <label for="website_url">网站URL</label>    <input type="text" class="form-control" id="website_url" placeholder="网站URL">   </div>    <button type="submit" class="btn btn-default">抓取</button>  </div> </div> <div class="panel panel-default">   <div class="panel-heading">文章URL</div>   <div class="panel-body">   <h3></h3>  </div> </div></div>

直接上代码,然后加上自己的一些样式调整,界面就完成啦:

那么接下来就是功能的实现了,我用PHP来写,首先第一步就是获取网站的html代码,获取html代码的方式也有很多,我就不一一介绍了,这里用了curl来获取,传入网站url就能得到html代码啦:

private function get_html($url){  $ch = curl_init();  $timeout = 10;  curl_setopt($ch, CURLOPT_URL, $url);  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);  curl_setopt($ch, CURLOPT_ENCODING, 'gzip');  curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.131 Safari/537.36');  curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);  $html = curl_exec($ch);  return $html; }

虽然得到了html代码,但是很快你会遇到一个问题,那就是编码问题,这可能让你下一步的匹配无功而返,我们这里统一把得到的html内容转为utf8编码:

$coding = mb_detect_encoding($html);if ($coding != "UTF-8" || !mb_check_encoding($html, "UTF-8"))$html = mb_convert_encoding($html, 'utf-8', 'GBK,UTF-8,ASCII');            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表