1. 使用curl,get獲得數據
<?php $url = 'http://www.example.com'; //初始化一個 cURL 對象 $ch = curl_init(); //設置你需要抓取的URL curl_setopt($ch, CURLOPT_URL, $url); // 設置cURL 參數,要求結果保存到字符串中還是輸出到屏幕上。 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //是否獲得跳轉后的頁面 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); $data = curl_exec($ch); curl_close($ch); echo $data; ?>
2. 使用curl,post獲得數據
<?php function curl_post($url, $arr_data){ $post_data = http_build_query($url_data); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFLELDS, $post_data); $data = curl_exec($ch); curl_close($ch); echo $data; } $arr_post = array( 'name'=>'test_name', 'age' => 1 ); curl_post("http://www.explame.com/", $arr_post); ?>
3. 使用代理抓取頁面
為什么要使用代理進行抓取呢?以google為例吧,如果去抓google的數據,短時間內抓的很頻繁的話,你就抓取不到了。google對你的ip地址做限制這個時候,你可以換代理重新抓。
<?php $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "http://google.com"); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //是否通過http代理來傳輸 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, TRUE); curl_setopt($ch, CURLOPT_PROXY, 125.21.23.6:8080); //url_setopt($ch, CURLOPT_PROXYUSERPWD, 'user:password');如果要密碼的話,加上這個 $result=curl_exec($ch); curl_close($ch); ?>
4.繼續保持本站session的調用
在實現用戶同步登錄的情況下需要共享session,如果要繼續保持本站的session,那么要把sessionid放到http請求中
<?php $session_str = session_name().'='.session_id().'; path=/; domain=.explame.com'; session_write_close(); //將數據寫入文件並且結束session $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_COOKIE, $session_str); $ret = curl_exec($ch); curl_close($ch); ?>