2011-05-24 38 views
1

嗨,我正在使用以下api從媒體維基獲取數據。當我複製此URL並將其粘貼到瀏覽器中時,會顯示一個xml響應。 http://en.wikipedia.org/w/api.php?action=query&prop=revisions&titles=API|Main_Page&rvprop=timestamp|user|comment|content我如何從媒體維基獲取數據

但是當我嘗試做捲曲它給我的錯誤「腳本應使用一個信息用戶代理字符串與聯繫人信息,也可能是封閉的IP,恕不另行通知。」

我正在使用下面的代碼。任何人都可以追蹤我的錯誤嗎?

$url='http://en.wikipedia.org/w/api.php?action=query&prop=revisions&titles=API|Main_Page&rvprop=timestamp|user|comment|content'; 
$curl = curl_init(); 
     curl_setopt($curl, CURLOPT_URL, $url); 
     curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); 
     //curl_setopt($curl, CURLOPT_TIMEOUT, 1); 
     $objResponse = curl_exec($curl); 
     curl_close($curl); 

     echo $objResponse;die; 

回答

0

這將工作繞過有引薦用戶代理檢查:

<?php 


    function getwiki($url="", $referer="", $userAgent="") { 
     if($url==""||$referer==""||$userAgent=="") { return false;}; 
     $headers[] = 'Accept: image/gif, image/x-bitmap, image/jpeg, image/pjpeg'; 
     $headers[] = 'Connection: Keep-Alive'; 
     $headers[] = 'Content-type: application/x-www-form-urlencoded;charset=UTF-8'; 
     $user_agent = $userAgent; 
     $process = curl_init($url); 
     curl_setopt($process, CURLOPT_HTTPHEADER, $headers); 
     curl_setopt($process, CURLOPT_HEADER, 0); 
     curl_setopt($process, CURLOPT_USERAGENT, $user_agent); 
     curl_setopt($process, CURLOPT_REFERER, $referer); 
     curl_setopt($process, CURLOPT_TIMEOUT, 30); 
     curl_setopt($process, CURLOPT_RETURNTRANSFER, 1); 
     curl_setopt($process, CURLOPT_FOLLOWLOCATION, 1); 
     $return = curl_exec($process); 
     curl_close($process); 
     return $return; 
    } 

    //edited to include Adam Backstrom's sound advice 
    echo getwiki('http://en.wikipedia.org/w/api.php?action=query&prop=revisions&titles=API|Main_Page&rvprop=timestamp|user|comment|content', 'http://en.wikipedia.org/', 'Mozilla/5.0 (compatible; YourCoolBot/1.0; +http://yoursite.com/botinfo)'); 

    ?> 
+1

請注意,不需要「Mozilla/5.0(compatible;」垃圾在那裏。瀏覽器只是爲了避免打破在愚蠢地檢查用戶代理和垃圾網站在不能識別的字符串上運行,只需將其設置爲「YourCoolBot/1.0; + http:// yoursite」 .com/botinfo「等。 – Anomie 2011-05-25 15:58:30

0

從MediaWiki的API:Quick start guide

傳遞一個User-Agent頭,妥善識別客戶:不要」不要使用客戶端庫中的默認用戶代理,而要使用自定義的用戶代理,包括客戶名稱和版本號,例如MyCuteBot/0.1。

在Wikimedia wiki上,未能提供用戶代理標頭或提供空白或通用標頭將導致請求失敗並出現HTTP 403錯誤。請參閱meta:User-Agent policy。其他MediaWiki wikis可能有類似的政策。

meta:User-Agent policy

如果你運行一個機器人,請發送User-Agent頭識別機器人和提供與您聯繫的一些方法,如:用戶代理:MyCoolTool(+ HTTP: //example.com/MyCoolToolPage/)