2016-05-24 44 views
1

我想解析通過http://whatismyip.com頁面並得到我的位置(州和國家)。數據似乎在<table class="table">標籤內,所以我正在尋找「表」。 但我得到一個錯誤Warning: file_get_contents(https://whatismyip.com): failed to open stream: HTTP request failed! HTTP/1.1 403 Forbidden in C:\xampp4\htdocs\scraping\libs\simple_html_dom.php on line 1081簡單的HTML DOM無法打開一個網站的流

無法弄清楚什麼是錯的。

<?php 
     require_once('libs/simple_html_dom.php'); 
     $html=new simple_html_dom(); 

     $html->load_file('https://whatismyip.com'); 

     $element=$html->find("table"); 


    ?> 
+0

看起來像whatismyip.com阻止你這樣做 – Brett

回答

3

該網站正在檢查請求的User-Agent頭,但PHP不發送任何(默認)。你必須要「冒充」瀏覽器:

$context = stream_context_create(array(
    'http' => array(
     'header' => array('User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; rv:2.2) Gecko/20110201'), 
    ), 
)); 

$html = file_get_contents('http://whatismyip.com/', false, $context); 

// do what you want with the $html 

更好,速度更快的辦法是使用一些庫這一點。我之前使用過GeoIP2-php,但我確定還有更多。

3

basicly您爲例它不錯,但這裏的錯誤是簡單的HTML DOM類不以https工作,所以嘗試另一種方法

$curl = curl_init(); 
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); 
curl_setopt($curl, CURLOPT_HEADER, false); 
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true); 
curl_setopt($curl, CURLOPT_URL, "https://whatismyip.com"); 
curl_setopt($curl, CURLOPT_REFERER, "https://whatismyip.com"); 
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE); 
curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 6.1; rv:2.2) Gecko/20110201'); 
$str = curl_exec($curl); 
curl_close($curl); 

,然後用你的代碼

$html->load_file($str); 
    $element=$html->find("table"); 

編輯添加用戶 - 代理模擬一個真正的導航器(感謝ShiraNai7)

+1

這也導致* HTTP 403 Forbidden *因爲User-Agent頭仍然從請求中缺失。 – ShiraNai7

+2

是的,可能是用戶代理有很大的影響,我推薦你這樣編碼,因爲我的代碼我只是給出了另一種方式來寫評論@ ShiraNai7 –

+1

添加'curl_setopt($ curl,CURLOPT_USERAGENT,'Mozilla/5.0 (Windows; U; Windows NT 6.1; rv:2.2)Gecko/20110201');'使這個代碼工作:) – ShiraNai7

0

嘗試更改用戶代理使用下面的命令 -

ini_set("user_agent","Mozilla/5.0 (Windows NT 6.1; rv:8.0) Gecko/20100101 Firefox/8.0"); 

它會正常工作!