-4

PHPでページから特定のクラスの最初の画像を取得しようとしています

<?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 />';
}
?>

このコードはページからすべての画像を取得します。このページからクラス「cnet-image」で画像を取得しようとしています

4

2 に答える 2

0

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]'); 
于 2012-11-07T09:41:15.033 に答える
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 で同じことを行う方法を知りたい場合はお知らせください。共有できます。

于 2012-11-07T09:47:03.173 に答える