抓取所有图片来自特定的div SRC
想,我有HTML结构,如:抓取所有图片来自特定的div SRC
<div>
<div class="content">
<p>This is dummy text</p>
<p><img src="a.jpg"></p>
<p>This is dummy text</p>
<p><img src="b.jpg"></p>
</div>
</div>
我想从.content
DIV获取所有图片src。我想:
<?php
// a new dom object
$dom = new domDocument;
// load the html into the object
$dom->loadHTML("example.com/article/2345");
// discard white space
$dom->preserveWhiteSpace = false;
//get element by class
$finder = new DomXPath($dom);
$classname = 'content';
$content = $finder->query("//*[contains(@class, '$classname')]");
foreach($content as $item){
echo $item->nodevalue;
}
但是,我不能当我遍历$content
得到任何东西。请帮忙。
更改您的XPath查询,如下图所示:
// loading html content from remote url
$html = file_get_contents("http://nepalpati.com/entertainment/22577/");
@$dom->loadHTML($html);
...
$classname = 'content';
$img_sources = [];
// getting all images within div with class "content"
$content = $finder->query("//div[@class='$classname']/p/img");
foreach ($content as $img) {
$img_sources[] = $img->getAttribute('src');
}
...
var_dump($img_sources);
// the output:
array(2) {
[0]=>
string(68) "http://nepalpati.com/mediastorage/images/2072/Falgun/khole-selfi.jpg"
[1]=>
string(72) "http://nepalpati.com/mediastorage/images/2072/Falgun/khole-hot-selfi.jpg"
}
我有一个空数组。 – user254153
@ user254153,哦,是的。只是一点点修复。看一下这个。它应该工作 – RomanPerekhrest
'$ dom-> loadHTML(“example.com/article/2345”); '没有为我加载任何html。有什么问题吗。 – user254153
安置自己的循环代码吗? – Vincent
是的。我发布了。 – user254153
我可以看到循环中的虚拟文本位,继承人 - https://3v4l.org/MXSK7,你确定你从example.com/article/2345获得的结构与你的样本结构相同吗? – Vincent