開發乙個爬蟲 PHP

2021-08-17 15:22:52 字數 3820 閱讀 8241

有時候因為工作、自身的需求,我們都會去瀏覽不同**去獲取我們需要的資料,於是爬蟲應運而生,下面是我在開發乙個簡單爬蟲的經過與遇到的問題。

開發乙個爬蟲,首先你要知道你的這個爬蟲是要用來做什麼的。我是要用來去不同**找特定關鍵字的文章,並獲取它的鏈結,以便我快速閱讀。

按照個人習慣,我首先要寫乙個介面,理清下思路。

[xhtml]view plain

copy

<

divclass

="jumbotron"id=

"mainjumbotron"

>

<

divclass

="panel panel-default"

>

<

divclass

="panel-heading"

>

文章url抓取

div>

<

divclass

="panel-body"

>

<

divclass

="form-group"

>

<

label

for=

"article_title"

>

文章標題

label

>

<

input

type

="text"

class

="form-control"id=

"article_title"

placeholder

="文章標題"

>

div>

<

divclass

="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>

<

divclass

="panel panel-default"

>

<

divclass

="panel-heading"

>

文章url

div>

<

divclass

="panel-body"

>

<

h3>

h3>

div>

div>

div>

直接上**,然後加上自己的一些樣式調整,介面就完成啦:

那麼接下來就是功能的實現了,我用php來寫,首先第一步就是獲取**的html**,獲取html**的方式也有很多,我就不一一介紹了,這裡用了curl來獲取,傳入**url就能得到html**啦:

[xhtml]view plain

copy

private function get_html($url)  

雖然得到了html**,但是很快你會遇到乙個問題,那就是編碼問題,這可能讓你下一步的匹配無功而返,我們這裡統一把得到的html內容轉為utf8編碼:

[php]view plain

copy

$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'

);  

得到**的html,要獲取文章的url,那麼下一步就是要匹配該網頁下的所有a標籤,需要用到正規表示式,經過多次測試,最終得到乙個比較靠譜的正規表示式,不管a標籤下結構多複雜,只要是a標籤的都不放過:(最關鍵的一步)

[php]view plain

copy

$pattern

= '|]*>(.*)|isu'

;  preg_match_all($pattern

, $html

, $matches

);  

匹配的結果在$matches中,它大概是這樣的乙個多維素組:

[js]view plain

copy

array(2)   

[1]=>  

array(*)   

}  只要能得到這個資料,其他就完全可以操作啦,你可以遍歷這個素組,找到你想要a標籤,然後獲取a標籤相應的屬性,想怎麼操作就怎麼操作啦,下面推薦乙個類,讓你更方便操作a標籤:

[php]view plain

copy

$dom

= new

domdocument();  

@$dom

->loadhtml(

$a);

//$a是上面得到的一些a標籤

$url

= new

domxpath(

$dom

);  

$hrefs

= $url

->evaluate(

'//a'

);  

for(

$i= 0; 

$i$hrefs

->length; 

$i++)   

當然,這只是一種方式,你也可以通過正規表示式匹配你想要的資訊,把資料玩出新花樣。

得到並匹配得出你想要的結果,下一步當然就是傳回前端將他們顯示出來啦,把介面寫好,然後前端用js獲取資料,用jquery動態新增內容顯示出來:

[php]view plain

copy

varwebsite_url = 

'你的介面位址'

;  $.getjson(website_url,function

(data)  

varstring = 

'';  

varlist = data.text;  

for(

varj in list)   

}  }  

$('#article_url'

).html(string);  

});  

上最終效果圖:

快速開發乙個PHP電影爬蟲

include once html dom.php 獲取html資料轉化為物件 html file get html a z的字母列表每條資料是在id letter focus 的div內class letter focus item的dl標籤內,用find方法查詢即為 listdata html ...

快速開發乙個PHP擴充套件

快速開發乙個php擴充套件 本文通過非常快速的方式講解了如何製作乙個php 5.2 環境的擴充套件 php extension 希望能夠在 的方式下讓想快速學習的朋友了解一下製作過程。步驟一 生成擴充套件框架 cd root soft php php 5.2.6 ext ext skel extna...

快速開發乙個PHP擴充套件

快速開發乙個php擴充套件 本文通過非常快速的方式講解了如何製作乙個php 5.2 環境的擴充套件 php extension 希望能夠在 的方式下讓想快速學習的朋友了解一下製作過程。步驟一 生成擴充套件框架 cd root soft php php 5.2.6 ext ext skel extna...