php file_get_contents 設定代理抓取頁面樣本

來源:互聯網
上載者:User


例1,普通頁面擷取

例如,訪問54master論壇,想抓取首頁裡 所有h3標記內的元素。

 代碼如下 複製代碼


$url=http://www.111cn.net;
$contents=@file_get_contents($url);
//preg_match_all("/<p class="right forumcount">(.*?)</p>/is",$contents,$content);
preg_match_all("/<h3>(.*?)</h3>/is",$contents,$content);
print_r($content[0]);

例2,設定代碼IP去採集資料

使用file_get_contents 和 stream_context_create 即可。

代碼如下:

 代碼如下 複製代碼

$aContext = array(
    'http' => array(
        'proxy' => 'tcp://192.168.0.2:3128',  //這裡設定你要使用的代理ip及連接埠號碼
        'request_fulluri' => true,
    ),
);
$cxContext = stream_context_create($aContext);
$sFile = file_get_contents("http://www.111cn.net", False, $cxContext);
echo $sFile;

以上代碼適用於正常情況,但是如果目標頁面需要登入或需要認證資訊才能訪問的話,可以加多一句代碼。

 代碼如下 複製代碼

$auth = base64_encode('LOGIN:PASSWORD');   //LOGIN:PASSWORD 這裡是你的賬戶名及密碼
$aContext = array(
    'http' => array(
        'proxy' => 'tcp://192.168.0.2:3128',  //這裡設定你要使用的代理ip及連接埠號碼
        'request_fulluri' => true,
        'header' => "Proxy-Authorization: Basic $auth",
    ),
);
$cxContext = stream_context_create($aContext);
$sFile = file_get_contents(http://www.111cn.net, False, $cxContext);
echo $sFile;

這樣就可以使用代理來抓取頁面或檔案了

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.