获取具有类 foo 的页面中的第一张图像

Get the first image in a page with class foo

提问人:Déjà Bond 提问时间:11/7/2012 最后编辑:j0kDéjà Bond 更新时间:11/7/2012 访问量:370

问:

我正在尝试通过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”的图像

PHP的

评论

0赞 George 11/7/2012
一些细节?甚至可能是一些代码?我们不是通灵的
0赞 Déjà Bond 11/7/2012
@F4r-20 我想 forums.digitalpoint.com/ 这张图片 forums.digitalpoint.com/showthread.php?t=1399697,我正在尝试从像这个页面这样的帖子页面获取第一个头像......
0赞 George 11/7/2012
PHP 是否用于生成具有指定图像的页面?
0赞 Déjà Bond 11/7/2012
@F4r-20 不,我想添加特定的页面链接,就像我使用它一样file_get_contents
0赞 Déjà Bond 11/7/2012
@F4r-20 我得到了一个代码,但需要一些关于特定类图像的帮助

答:

0赞 William Isted 11/7/2012 #1

您应该能够使用 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赞 mwangi 11/7/2012 #2

我假设您想检索 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赞 Déjà Bond 11/7/2012
谢谢,但我需要它和 PHP 一起从另一个页面而不是同一页面获取图像
0赞 mwangi 11/7/2012
啊哈好的。我没有从这个问题中获得足够的信息来回答你。也许您可以尝试搜索检索到的 HTML 字符串?