2013-11-26 52 views
1

有人可以展示如何在抓取每個元素<a href>時獲得鏈接並獲取其相關信息嗎?simplehtmldom - 關注鏈接

$html = file_get_html('http://www.blabla.com/'); 
$html->find('div', 1)->class = 'bar'; 

現在每個<li>有一個鏈接到更多信息

<li class="#Selected"> 
<a href="/contactinfo/ITService/">info</a> 
<h2>New York</h2> 
<h3>USA</h3> 
<strong>ITService</strong> 
</li> 

然後:

<div class="InfoD"> 
<h2>New York</h2> 
<h3>USA</h3> 
<strong>ITService</strong> 
<p> 
Tel. : XXXXXX 
</p> 
<p> 
Mail. : [email protected]  
</p> 
</div> 

我知道如何使用HTML DOM刮這樣的元素,但是當有每個元素鏈接和多個頁面,我不知道如何..如果任何人都可以指向一個例子或任何類似的教程。由於

回答

2

首先你會被從li.#Selected a的所有鏈接,那麼你犯了一個循環,從每一個得到div.InfoD ...

這裏是展示如何代碼片段:

// includes Simple HTML DOM Parser 
include "simple_html_dom.php"; 

$url = "http://www.blabla.com/"; 

$baseUrl= "http://www.blabla.com" 

//Create a DOM object 
$html = new simple_html_dom(); 
// Load HTML from a URL 
$html->load_file($url); 

// Get all links 
$anchors = $html->find('li.#Selected a'); 

// loop through each link and get the node having "InfoD" class 
// Everytime make sure to clear dom objects to avoid memory leaks 
foreach ($anchors as $anchor) { 

    // Create the new link to parse 
    $urlTemp = $baseUrl . $anchor->href; 

    //Create a DOM object 
    $html2 = new simple_html_dom(); 
    // Load HTML from a URL 
    $html2->load_file($urlTemp); 

    // Get all nodes with "text-logo" 
    $div = $html->find('div.InfoD', 0); 

    echo $div; 
    echo "<hr/>"; 

    // Clear dom object 
    $html2->clear(); 
    unset($htm2); 

} 

// Clear dom object 
$html->clear(); 
unset($html); 
+0

這將是最好的簡單地自動跟蹤鏈接並從詳細信息頁面中提取完整內容的方法? – Natalia

+1

@Natalia,['This'](http://stackoverflow.com/a/21292873/1519058)可能有幫助... – Enissay