2010-11-13 141 views
3

我正在使用PHP試圖抓取頁面,似乎在父頁面加載完成後僅僅幾毫秒就動態加載內容。PHP:延遲解析頁面源代碼(通過file_get_html())1秒

我使用curl來解析頁面,而simpleHtmlDom從解析的html中抓取事物。我的努力遍歷DOM和爆炸()的東西出來的HTML返回什麼都沒有。我唯一的想法是加載了之後的加載了父頁面。

這是我的代碼。

<? 
$url = 'http://www.facebook.com/OneAndroidAppaDay'; 
$scrapeUrl = 'http://www.facebook.com/OneAndroidAppaDay'; 

    include_once('simple_html_dom.php'); 
    require_once("bitly.php"); 

    $userAgent = 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)'; 
    $ch = curl_init(); 
    curl_setopt($ch, CURLOPT_USERAGENT, $userAgent); 
    curl_setopt($ch, CURLOPT_URL,$scrapeUrl); 
    curl_setopt($ch, CURLOPT_FAILONERROR, true); 
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); 
    curl_setopt($ch, CURLOPT_AUTOREFERER, true); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,true); 
    curl_setopt($ch, CURLOPT_TIMEOUT, 10); 
    $html = curl_exec($ch); 
    if (!$html) { 
    echo "<br />cURL error number:" .curl_errno($ch); 
    echo "<br />cURL error:" . curl_error($ch); 
    exit; 
    } 

    $appBitlyUrl = $html->find('div[class=UIStoryAttachment_Title]',0)->find('a',0)->href; // fail :(
    echo 'Bitly Url: ' . $appBitlyUrl; 
?> 

它與此錯誤轟炸了在第24行(與行內註釋表示):

Fatal error: Call to a member function find() on a non-object in /home/xxxxxxxx/public_html/xxx.xx/xxxx.php on line 24

有沒有辦法讓它等待一兩秒鐘就搶頁面的HTML之前?或者,也許有人有更好的見解?

感謝

馬克

+2

任何類型的延遲都與您當前擁有的錯誤消息無關。 – zerkms 2010-11-13 03:39:39

+1

順便說一句,刮臉在Facebook的任何應用程序的內容是超出他們的TOS和非法,downvoted。 – zerkms 2010-11-13 03:40:15

+0

Upvoted回零。這不是一個法律諮詢網站。除了Facebook沒有對用戶貢獻的內容擁有版權的權力之外,對個人使用的欺騙也很少是非法的。 (是的,我知道我也在做假設。) – mario 2010-11-13 04:11:43

回答

1

做一個簡單的延遲

sleep(2); // 2 second delay before continuing 
0

你真的應該重新讀取錯誤消息。它不是源於時間問題。

您從curl中獲得一個$ html字符串。但是你不能調用phphtmldom函數 - >馬上找到它。你必須在遍歷之前解析它。另外還不清楚你爲什麼首先使用捲曲。請僅使用$dom = str_get_html($html)或嘗試:

$dom = file_get_html('http://www.facebook.com/OneAndroidAppaDay'); 

$bituurl = $dom->find('div[class=UIStoryAttachment_Title]',0)->... 
+0

我過去一直在使用file_get_html(),它仍然會拋出相同的錯誤。我認爲它只是試圖去探索那些還沒有的東西。 – 2010-11-13 19:11:20

+0

@ marky-b:那肯定是一個simplehtmldom的bug。 'print_r'無論你回來看看它是否是一個對象。否則,請嘗試解析str_variant。或者更好的遷移到phpQuery或QueryPath,這是兩種不錯的選擇。 – mario 2010-11-13 19:27:30