2013-04-06 63 views
2

我試圖弄到一個php簡單的html dom,我在遇到div類時遇到了一些問題。使用php簡單的html dom或phpQuery查找div class值

例如,對newegg說,我想找到div class'skiplink的值(我剛剛在網站上選擇了一個隨機類)。根據php簡單的html dom文檔發現here我應該只用。

$html = file_get_html('http://www.newegg.com'); 

print_r($ret = $html->find('.skiplink')); 

現在它只是掛起,似乎凍結。我知道安裝正在工作,因爲下面的代碼工作。

foreach($html->find('a') as $element) 
    echo $element->href . '<br>'; 

基本上,我該如何看待特定網站上的特定div類並找到該值?

有沒有做到這一點,如用phpQuery

+0

你嘗試'的var_dump($ HTML的「發現( '.skiplink'));'? – 2013-04-06 02:20:05

+0

爲什麼不只是使用[DOMDocument](http://php.net/manual/en/class.domdocument.php)? – egig 2013-04-06 02:36:43

+0

@AlfredXing鉻在我嘗試時崩潰。 – user1406951 2013-04-06 02:55:57

回答

0

從這個網站一個簡單的搜索更簡單的方法:How to get value from <div>value</div>?

但這裏是他們在說什麼;

$doc = new DomDocument(); 
$doc->loadHTMLFile('http://www.results.com'); 
$thediv = $doc->getElementById('result'); 
echo $thediv->textContent; 

或者你可以通過獲取id的值來找到div子句的innerText值;

$div = $doc->getElementById('result'); 
if($div) { 
    echo $div->textContent; 
} 
+0

我得到的錯誤幾乎所有我嘗試。假設我想在newegg上找到[此處]找到的物品的價格(http://www.newegg.com/Special/ShellShocker.aspx?cm_sp=ShellShocker-_-32-562-001-_-04062013_1)。它的ID是ltFrequentlyBoughtItemFinalPrice0。當我使用你顯示的代碼時,我得到了一堆錯誤,比如「Warning:DOMDocument :: loadHTMLFile()[domdocument.loadhtmlfile]:htmlParseEntityRef:expectcting';'」 – user1406951 2013-04-06 19:18:13

0

或使用XPath來代替,這個代碼將出來把SRC

//init DOMDocument 
$dom = new DOMDocument(); 
//get the source from the URL 
$html = file_get_contents("URL"); 
//load the html 
dom->loadHTML($html); 
//init XPath 
$xpath = new DOMXPath($dom); 

//fetch the src from the iframe within a class name 
$iframe_src=$xpath->query('//*[@class="CLASSNAME"]/iframe//@src'); 

vardump($iframe_src); 

要獲得內容使用file_get_contents()

$options = array('http' => array('user_agent' => 'USERAGENT')); //you must specify a user agent 
$context = stream_context_create($options); 
$response = file_get_contents($iframe_src, false, $context);