2012-11-07 14 views
-4

我試圖通過PHP
獲得第一個圖像中的頁面與類Foo

<?php 
$document = new DOMDocument(); 
@$document->loadHTML(file_get_contents('http://www.cbsnews.com/8301-501465_162-57471379-501465/first-picture-on-the-internet-turns-20/')); 
$lst = $document->getElementsByTagName('img'); 

for ($i=0; $i<$lst->length; $i++) { 
    $image = $lst->item($i); 
    echo $image->attributes->getNamedItem('src')->value, '<br />'; 
} 
?> 

獲得與特定網頁類的第一個圖像的代碼獲得從頁面的所有圖像,我是現在試圖從this page

+0

一些細節?也許甚至有些代碼?我們不是通靈 – George

+0

使用dom解析器 –

+0

@ F4r-20我試圖從頁面這樣的頁面獲得第一個頭像http://forums.digitalpoint.com/showthread.php?t=1399697我想要得到此圖片http://forums.digitalpoint.com/image.php?u=246759&dateline=1256890274 –

回答

0

獲得具有類「cnet-image」的圖像您應該能夠使用Simple HTML Dom做你需要的東西,試試看,我用它來做幾個類似的東西,包括圖像爬蟲。 http://simplehtmldom.sourceforge.net/

它看起來像你應該能夠使用你所需要的以下內容。

// Create DOM from URL or file 
$html = file_get_html('http://www.google.com/'); 

$ret = $html->find('img[class=foo]'); 
+0

我得到了簡單的代碼,但需要一些特定的類的幫助 –

0

我推測你想要在HTML文檔中檢索具有特定類屬性名稱的第一個圖像。 如果是這樣,那麼這可能會有所幫助。

var l = document.images; 
var myclass = "myclass";//This is the class you want 
var firstImageWithMyClass = null; 

for(var i = 0; i<l; i++) 
    if(document.images[i].className==myclass){ 
    firstImageWithMyClass = document.images[i]; 
    break; 
    } 

//Then you can see if an image with that class was found, 
//then do what you want to do withit here; 
if(firstImageWithMyClass!=null){ 
    var imageSource = firstImageWithMyClass.src; 
    //etc, etc 
} 

jQuery使這更容易。讓我知道如果你想知道如何做與jQuery相同,我可以與你分享。

+0

謝謝你,但我需要它與PHP來從另一個頁面的圖像不是相同的頁面 –

+0

阿哈好。我沒有足夠的信息來回答你的問題。也許你可以嘗試搜索你檢索的HTML字符串? – mwangi

相關問題