1. 程式人生 > 實用技巧 >PHP爬取網頁的主要方法,你掌握了嗎

PHP爬取網頁的主要方法,你掌握了嗎

這篇文章講的是PHP爬取網頁的主要方法,主要流程就是獲取整個網頁,然後正則匹配(關鍵的)。

PHP抓取頁面的主要方法,有幾種方法是網上前輩的經驗,現在還沒有用到的,先存下來以後試試。

  1. file()函式
  2. file_get_contents()函式
  3. fopen()->fread()->fclose()模式
  4. curl方式 (本人主要用這個)
  5. fsockopen()函式 socket模式
  6. 外掛(如:http://sourceforge.net/projects/snoopy/)

不要走開,接下來就分別來看看這六種方法,你掌握了幾個?

1.file()函式

<?php
//定義url $url='[http://t.qq.com](http://t.qq.com/)';//fiel函式讀取內容陣列 $lines_array=file($url);//拆分陣列為字串 $lines_string=implode('',$lines_array);//輸出內容 echo $lines_string;

2.使用file_get_contents方法實現,比較簡單。

使用 file_get_contents 和fopen必須空間開啟 allow_url_fopen 。方法:編輯php.ini,設定 allow_url_fopen = On,allow_url_fopen 關閉時fopen和 file_get_contents 都不能開啟遠端檔案。

$url="[http://news.sina.com.cn/c/nd/2016-10-23/doc-ifxwztru6951143.shtml](http://news.sina.com.cn/c/nd/2016-10-23/doc-ifxwztru6951143.shtml)";

$html=file_get_contents($url);

//如果出現中文亂碼使用下面程式碼`

//$getcontent = iconv("gb2312", "utf-8",$html);

echo"<textarea style='width:800px;height:600px;'>".$html."</textarea>";

3.fopen()->fread()->fclose()模式 ,目前還沒用過,看到了就先記下了

<?php

//定義url

$url='[http://t.qq.com](http://t.qq.com/)';//fopen以二進位制方式開啟

$handle=fopen($url,"rb");//變數初始化

$lines_string="";//迴圈讀取資料

do{

$data=fread($handle,1024); 

if(strlen($data)==0) {`

break;

}

$lines_string.=$data;

}while(true);//關閉fopen控制代碼,釋放資源

fclose($handle);//輸出內容

echo $lines_string;

4.使用curl實現(本人一般使用這個)。

使用 curl 必須空間開啟 curl 。方法:windows下修改 php.ini ,將 extension=php_curl.dll 前面的分號去掉,而且需 要拷貝 ssleay32.dll 和 libeay32.dll 到 C:\WINDOWS\system32 下;Linux下要安裝 curl 擴充套件。

<?php

header("Content-Type: text/html;charset=utf-8");

date_default_timezone_set('PRC');

$url = "https://***********ycare";//要爬取的網址

$res = curl_get_contents($url);//curl封裝方法

preg_match_all('/<script>(.*?)<\/script>/',$res,$arr_all);//這個網頁中資料通過js包過來,所以直接抓js就可以

preg_match_all('/"id"\:"(.*?)",/',$arr_all[1][1],$arr1);//從js塊中匹配要的資料

$list = array_unique($arr1[1]);//(可省)保證不重複

//以下則是同理,迴圈則可

for($i=0;$i<=6;$i=$i+2){

  $detail_url = 'ht*****em/'.$list[$i];

  $detail_res = curl_get_contents($detail_url);

  preg_match_all('/<script>(.*?)<\/script>/',$detail_res,$arr_detail);

  preg_match('/"desc"\:"(.*?)",/',$arr_detail[1][1],$arr_content);

  ***

    ***

    ***

  $ret=curl_post('http://**********cms.php',$result);//此指令碼未放在伺服器上,原因大家懂就好哈。

}

function curl_get_contents($url,$cookie='',$referer='',$timeout=300,$ishead=0) {

  $curl = curl_init();

  curl_setopt($curl, CURLOPT_RETURNTRANSFER,1);

  curl_setopt($curl, CURLOPT_FOLLOWLOCATION,1);

  curl_setopt($curl, CURLOPT_URL,$url);

  curl_setopt($curl, CURLOPT_TIMEOUT,$timeout);

  curl_setopt($curl, CURLOPT_USERAGENT,'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36');

  if($cookie)

  {

    curl_setopt( $curl, CURLOPT_COOKIE,$cookie);

  }

  if($referer)

  {

  curl_setopt ($curl,CURLOPT_REFERER,$referer);

  }

  $ssl = substr($url, 0, 8) == "https://" ? TRUE : FALSE;

  if ($ssl)

  {

    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);

    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

  }

  $res = curl_exec($curl);

  return $res;

  curl_close($curl);

}

//curl post資料到伺服器

function curl_post($url,$data){

  $ch = curl_init();

  curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);

  //curl_setopt($ch,CURLOPT_FOLLOWLOCATION, 1);

  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

  curl_setopt($ch,CURLOPT_USERAGENT,'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36');

  curl_setopt($ch,CURLOPT_URL,$url);

  curl_setopt($ch,CURLOPT_POST,true);

  curl_setopt($ch,CURLOPT_POSTFIELDS,$data);

  $output = curl_exec($ch);

  curl_close($ch);

  return $output;

}

?>

5.fsockopen()函式 socket模式(沒用過,以後可以試試)

socket 模式能否正確執行,也跟伺服器的設定有關係,具體可以通過 phpinfo 檢視伺服器開啟了哪些通訊協議

<?php

$fp = fsockopen("t.qq.com", 80, $errno, $errstr, 30);

if (!$fp) {

  echo "$errstr ($errno)<br />\n";

} else {

  $out = "GET / HTTP/1.1\r\n";

  $out .= "Host: t.qq.com\r\n";

  $out .= "Connection: Close\r\n\r\n";

  fwrite($fp, $out);

  while (!feof($fp)) {

    echo fgets($fp, 128);

  }

  fclose($fp);

}

6.snoopy外掛(最新版本是Snoopy-1.2.4.zip Last Update: 2013-05-30,推薦大家使用)

使用網上非常流行的 snoopy 來進行採集,這是一個非常強大的採集外掛,並且它的使用非常方便,你也可以在裡面設定 agent 來模擬瀏覽器資訊。

說明:設定 agent 是在 Snoopy.class.php 檔案的第45行,請在該檔案中搜索 “var 公式輸入有誤
_SERVER[‘HTTP_USER_AGENT’]; 可以得到瀏覽器資訊,將 echo 出來的內容複製到 agent 裡面就可以了。

<?php

//引入snoopy的類檔案

require('Snoopy.class.php');

//初始化snoopy類

$snoopy=new Snoopy;

$url="[http://t.qq.com](http://t.qq.com/)";

//開始採集內容`

$snoopy->fetch($url);

//儲存採集內容到$lines_string

$lines_string=$snoopy->results;

//輸出內容,嘿嘿,大家也可以儲存在自己的伺服器上

echo $lines_string;

更多學習內容可以訪問從碼農成為架構師的修煉之路