2015-11-01 73 views
1

我正在使用的庫是:PHP Simple HTML DOM Parser v1.5.0爲什麼「PHP Simple HTML DOM解析器」有時無法解析HTML body?

與一些網址,它的str_get_html()和file_get_html()調用將返回false。例如:

$html = HtmlDomParser::file_get_html('http://finance.yahoo.com/'); 

我該如何解決這個問題?

+6

使用他們的財務api而不是刮頁面,問題解決了。 – 2015-11-01 21:23:15

+1

@Dagon,你假設我試圖抓取財務數據;但我想要做的是刮頁數據。另外,這只是我遇到的最近的一個例子。其他網址也是這樣。 –

+0

我會強烈建議使用[DOMDocument](http://php.net/manual/en/class.domdocument.php) – Machavity

回答

0

簡單的HTML DOM解析器supports invalid HTML。 但問題可能是加載雅虎頁面,頁面上的各種轉發......捲曲可以應付的所有事情。 如此快速,骯髒,可能是處理這種情況的最糟糕方式是使用變通方法 - 使用cURL加載頁面內容,然後使用Simple HTML DOM代碼解析變量。

事情是這樣的:

<?php 
include('simple_html_dom.php'); 

$search_url = 'http://finance.yahoo.com/'; 

function bCurl($url) { 

    $cookie_file = "cookie1.txt"; 

    $header = array(); 
    $header[] = 'Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5'; 
    $header[] = 'Cache-Control: max-age=0'; 
    $header[] = 'Connection: keep-alive'; 
    $header[] = 'Keep-Alive: 300'; 
    $header[] = 'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7'; 
    $header[] = 'Accept-Language: en-us,en;q=0.5'; 
    $header[] = 'Pragma: '; 
    $ch = curl_init(); 
    curl_setopt($ch, CURLOPT_URL, $url); 
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.11) Gecko/2009060215 Firefox/3.0.11 (.NET CLR 3.5.30729)'); 
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header); 
    curl_setopt($ch, CURLOPT_AUTOREFERER, true); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); 
    curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file); 
    curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file); 
    curl_setopt($ch, CURLOPT_ENCODING, ''); 
    curl_setopt($ch, CURLOPT_TIMEOUT, 20); 
    $result = curl_exec($ch); 
    curl_close ($ch); 

    return $result; 
} 

$result = bCurl($search_url); 

$html = new simple_html_dom(); 
$html->load($result); 

$keywords = $html->find("meta[name=keywords]",0)->getAttribute('content'); 

print_r($keywords); 
?> 

妥善解決可能會被分析雅虎財經頁面,查看發生了什麼事情在那裏,分析轉發和抗刮機制,JavaScript和Flash對象......但是,嘿,我們都像這樣的即時,快速和骯髒的解決方案,對不對? ;)