提问人:Déjà Bond 提问时间:11/7/2012 最后编辑:j0kDéjà Bond 更新时间:11/7/2012 访问量:370
获取具有类 foo 的页面中的第一张图像
Get the first image in a page with class foo
问:
我正在尝试通过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”的图像
答:
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 字符串?
评论