【发布时间】:2014-03-30 20:41:19
【问题描述】:
我有一个问题,我不明白为什么会这样。在某些我在 img 中有 data-thumb 的元素上,它不会抓取图像 src 元素,我不知道为什么。
这是一个如何格式化 html 页面的示例。我们称之为 somepage.com/search?q=singing
<div class="videos">
<div class="thumbWrapper">
<div class="postThumbnail">
<img id="2019485" class="videoThumb" width="190" height="143" alt="some post title" src="http://imageurl.com/uploaded/image/3.jpg" category="7">
</div>
</div>
<div class="thumbWrapper">
<div class="postThumbnail">
<img id="2019485" class="videoThumb" width="190" height="143" alt="some post title" data-thumb="http://imageurl.com/uploaded/image/3.jpg" src="http://imageurl.com/uploaded/image/3.jpg" category="7">
</div>
</div>
<div class="thumbWrapper">
<div class="postThumbnail">
<img id="2019485" class="videoThumb" width="190" height="143" alt="some post title" data-thumb="http://imageurl.com/uploaded/image/3.jpg" src="http://imageurl.com/uploaded/image/3.jpg" category="7">
</div>
</div>
<div class="thumbWrapper">
<div class="postThumbnail">
<img id="2019485" class="videoThumb" width="190" height="143" alt="some post title" src="http://imageurl.com/uploaded/image/3.jpg" category="7">
</div>
</div>
</div>
您会看到某些图像上有 data-thumb,这完全是随机的,有些有,有些没有,在同一页面上。
这是我抓取页面的方式
$get = curl_init();
curl_setopt($get, CURLOPT_USERAGENT,'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');
curl_setopt($get, CURLOPT_URL, 'somepage.com/search?q=singing');
curl_setopt($get, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($get, CURLOPT_CONNECTTIMEOUT, 10);
$str = curl_exec($get);
curl_close($get);
$URL = str_get_html($str);
这行得通,或者至少我看到它行得通,下一步是从页面中提取元素并获取这些拇指。
foreach($URL->find('div[class="thumbWrapper"]') as $video) {
$thumb = $video->find('img[class="videoThumb"]');
$image = $thumb[0]->src;
}
我遇到了问题,在我拥有的 img 元素上
data-thumb
它不会得到图像。
在 simplehtmldom 页面上,它只是说我需要使用 like
$video->find('img');
$thumb->src;
但它不起作用,我必须指定 img 类并使用数组的 [0]。但我猜当有 data-thumb 数组被移动所以 src 在数组中不是更多 [0] 时?
我不知道我刚开始使用 simplehtmldom 还在学习中,有什么建议吗?
【问题讨论】:
-
你使用了错误的类。
postThumbnail不是图像的类别。你想做什么? -
是的,这是一个错字,在我的代码上我检查了类没有错。我在下面发布的解决方案对我有用。
标签: php image src simple-html-dom