0

我正在尝试从网页中提取图像。

我正在使用以下代码,但它没有输出,尽管我知道那里有一些(以 ebay 页面为例)

$html = "http://www.ebay.co.uk/itm/190706137456?_trkparms=clkid%3D1088812801530482649&_qi=RTM944765";
$dom = new domDocument;
@$dom->loadHTML($html);
$dom->preserveWhiteSpace = false;
$images = $dom->getElementsByTagName('img');
foreach ($images as $image) {
echo $image->getAttribute('src');
}

除此之外,是否可以仅提取 jpg 图像,然后仅提取高于特定高度/宽度尺寸的图像?

我最近一直在使用 simple_html_dom,但它很多时候都失败了,而且我发现它很慢。

有没有办法,例如,而不是寻找 'img' 和 'src' 来找到以 '.jpg' 结尾的任何内容,而在 'http://...etc etc..' 之前删除所有内容

4

1 回答 1

0

尝试使用 $dom->loadHTMLFile() 而不是 $dom->loadHTML。所以...

$html = "http://www.ebay.co.uk/itm/190706137456?_trkparms=clkid%3D1088812801530482649&_qi=RTM944765";
$dom = new domDocument();
$dom->loadHTMLFile($html);

您可以在 foreach() 循环中过滤图像类型(并仅获取文件名)。尝试这样的事情:

$images = $dom->getElementsByTagName('img');
foreach ($images as $image) {
  $filename = basename($image->getAttribute('src'));
  $ext = pathinfo($filename, PATHINFO_EXTENSION);
  if ($ext == 'jpg') {
     echo $filename . '<br>';
  }
}

您还可以按图像宽度和高度进行过滤,但它如何找到宽度和高度似乎很奇怪。你会想象通过使用这些属性......

$width = $image->getAttribute('width');
$height = $image->getAttribute('height');

...它会吐出 width="xxx" 和 height="yyy" ...但它不会。看起来它取而代之的是样式属性。所以记住这一点。话虽如此,您也可以对宽度和高度使用类似的解决方案。像这样:

$images = $dom->getElementsByTagName('img');
foreach ($images as $image) {
   $filename = basename($image->getAttribute('src'));
   $width = $image->getAttribute('width');
   $height = $image->getAttribute('height');
   $ext = pathinfo($filename, PATHINFO_EXTENSION);
   if ($ext == 'jpg' && ($width > 20 && $height > 10)) {
      echo $filename . "($width x $height)" . '<br>';
   }
}

希望这对你有用。一切都在这里,以备不时之需:

$html = "http://www.ebay.co.uk/itm/190706137456?_trkparms=clkid%3D1088812801530482649&_qi=RTM944765";
$dom = new domDocument();
$dom->loadHTMLFile($html);
$dom->preserveWhiteSpace = false;
$images = $dom->getElementsByTagName('img');
foreach ($images as $image) {
   $filename = basename($image->getAttribute('src'));
   $width = $image->getAttribute('width');
   $height = $image->getAttribute('height');
   $ext = pathinfo($filename, PATHINFO_EXTENSION);
   if ($ext == 'jpg' && ($width > 20 && $height > 10)) {
      echo $filename . "($width x $height)" . '<br>';
   }
}
于 2012-08-04T16:47:14.697 回答