ajax+php實現爬蟲功能

alansleep發表於2013-02-18

本文綜合php,ajax的基礎知識來做次很酷的事-爬蟲,代理. 作為練習,這裡僅僅實現抓去別人頁面上的圖片顯示在自己的頁面上---這已經很酷了.
1.域安全限制:
在js裡是訪問不了不同域下面的檔案的.除非那目標網站是你的,而且你能對要訪問的頁面進行修改.但是任何網站都不會限制客戶端的正常訪問請求.所以,我們先在自己的網站實現一個代理頁面.這東西和原來經常出現的翻牆工具一樣.
2.php代理:

<?php
//dl.php
require_once("simple_html_dom.php");
$user_agent= "Mozilla/4.0"; //瀏覽器
$url = '';

if ($_GET['p']) {
    $url = $_GET['p'];
    $url = base64_decode($url);
}

if($url)
{
    $session = curl_init();
    curl_setopt($session,CURLOPT_URL,$url);
    curl_setopt($session, CURLOPT_HEADER, false);
    curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
    $lofter = curl_exec($session);
    curl_close($session);

    $html = str_get_html($lofter);
    $url = $html->find('textarea[name=js]', 0)->innertext;
    $html->clear();
    $ibpos = stripos ($url,'\'');
    $iepos = stripos($url,'\'', $ibpos + 1);
    $url = substr($url,$ibpos + 1,$iepos - $ibpos  - 1);
    echo '<img src = "'.$url.'"/>';
}
?>

第1行是引入一個很好用的dom工具類.有他可以很方便的獲取修改各個節點的資訊.名字就是simplehtmldom.很簡單方便.把他想象成c/cpp經常用的tinyxml也可以.
6-9行是看通過get方法傳進來的結果base64編碼過的網站地址.
13-18通過curl抓去頁面.
20-22通過simplehtmldom獲取一個節點的內容.
後面通過字串操作修剪得到自己要的內容.這裡是得到其中的一個圖片地址.你完全可以做到得到裡面你想要的任何資料,入庫等.

ok,先訪問這個頁面,傳入正確的引數,如:http://epics.cn/dl.php?p=aHR0cDovL3d3dy5sb2Z0ZXIuY29tLw== .還不錯的樣子.

3,自己的頁面lofter.html

<html>
<head>
     <title>Lofter</title>
     <script src="lofter.js"></script>
</head>
<body>
     <p>
        <a id="makeImgRequest" href="#">Get</a>   
     </p>
     <div id="ImgArea"> </div>
</body>
</html>

這個頁面就一個連結和準備顯示抓來的圖片. 重要的工作是在js裡做的.

4,ajax~:
ajax有很多好處,最醒目的估計就是讓web程式看起來更像本地應用程式的風格-反應快.原理也簡單,搜尋就知道了.
lofter.js

window.onload = initAll; 
var xhr = false;

function initAll() {
     document.getElementById("makeImgRequest").onclick = getNewFile;
}

function getNewFile() {
     makeRequest();
     return false;
}

function makeRequest() {
     if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest();
     }
     else {
        if (window.ActiveXObject) {
           try {
              xhr = new ActiveXObject("Microsoft.XMLHTTP");
           }
           catch (e) { }
        }
     }

     if (xhr) {
        xhr.onreadystatechange = showContents;
        xhr.open("GET", 'dl.php?p=aHR0cDovL3d3dy5sb2Z0ZXIuY29tLw==', true);
        xhr.send(null);
     }
     else {
        document.getElementById("ImgArea").innerHTML = "Sorry, but I couldn't create an XMLHttpRequest";
     }
}

function showContents() {
    var outMsg = "";
    if (xhr.readyState == 4) {
        if (xhr.status == 200) {
            if (xhr.responseXML && xhr.responseXML.childNodes.length > 0) {
                var bg = xhr.responseXML.getElementsById ("bg");
                var outMsg = getText(xhr.responseXML.getElementsById ("bg"));
            }
            else {
                var outMsg = xhr.responseText;

            }
        }
        else {
            var outMsg = "There was a problem with the request " + xhr.status;
        }
        document.getElementById("ImgArea").innerHTML = outMsg;
     }

     function getText(inVal) {
        if (inVal.textContent) {
           return inVal.textContent;
        }
        return inVal.text;
     }
}   

程式碼都是套路.過程就是非同步獲取到同域下的檔案,還記得前面說的'一般情況下js不能訪問不同域的檔案'嗎.通過代理獲取並且分析過濾得到的一個圖片地址.然後更新到頁面的imgarea節點下.

效果如:http://epics.cn/lofter.html over~

我的部落格

相關文章