【问题标题】:getting the main image from another url?从另一个网址获取主图像?
【发布时间】:2016-07-13 01:38:40
【问题描述】:

我有一个函数可以返回任何网页的所有 img 链接,但我想获取最能代表新闻文章的图像。我知道这是一个有点难的问题,但每篇新闻文章的顶部都有一些主要图片。我需要在所有其他图像中挑选它。 Facebook 和 reddit 之类的网站可以做到这一点。你有什么想法吗?当我的网站成员分享链接时,应该有图片。我现在可以在网页中获取所有图像的 url,我需要找到主图像。 :)

function get_links($url) {

$xml = new DOMDocument();

libxml_use_internal_errors(true);

$html = file_get_contents($url);

if(!$xml->loadHTML($html)) {
    $errors="";
    foreach (libxml_get_errors() as $error)  {
        $errors.=$error->message."<br/>";
    }
    libxml_clear_errors();
    print "libxml errors:<br>$errors";
    return;
}

// Empty array to hold all links to return 
$links = array();

//Loop through each <img> tag in the dom and add it to the link array 
foreach ($xml->getElementsByTagName('img') as $link) {
    $url = $link->getAttribute('src');
    if (!empty($url)) {
        $links[] = $link->getAttribute('src');
    }
}

//Return the links 
return $links;
}

【问题讨论】:

  • 查看Open Graph,如果这些元标记存在,使用它们可能是明智之举,例如&lt;meta property="og:image" content="http://www.whatever.com/image.png" /&gt;,否则您所要做的就是图像大小属性或自己下载内容。另外,你得到了我对使用 DOMDocument 的投票!
  • 如果你要反对像 CNN.com 这样的文章结构一致的网站,我会先使用控制台检查你所追求的图像,看看它是否有某种类型的命名约定。例如,看起来大多数 CNN 文章的主图像上都有一个容器,带有以下类 zn zn-large-media zn-body zn--idx-0 zn-has-one-container 但是,我不能保证所有文章都是一样的......
  • CNN 是开放图使用的一个很好的例子,例如 this article 有以下标签 &lt;meta content="http://i2.cdn.turner.com/cnnnext/dam/assets/160510183508-hillary-clinton-bernie-sanders-cnn-debate-large-tease.jpg" property="og:image"&gt;
  • 感谢 cnn.com 是一个例子,我知道没有任何 100% 的解决方案。我只是希望我的代码应该为用户共享的每个链接生成一个合适的图像
  • 我可能会检查图像大小,更大的图像往往更好或文章,标题标签可能具有链接的最佳可能图像。我真的很想知道其他大网站是如何处理它的。比如 facebook 或 reddit。他们经常为用户帖子找到最佳图片。

标签: php html


【解决方案1】:

您可以改进现有功能,但如果您想优先考虑 Open Graph 数据的存在,请将其添加到您的 getElementsByTagName('img') 逻辑之前...

$xpath = new DOMXPath( $xml );
if( $xpathNodeList = $xpath->query('//meta[@property="og:image" and @content]') )
{
  return array( $xpathNodeList->item(0)->getAttribute('content') );
}

或将其添加到您的数组中...

// Empty array to hold all links to return
$links = array();

$xpath = new DOMXPath( $xml );
if( $xpathNodeList = $xpath->query('//meta[@property="og:image" and @content]') )
{
  $links[] = $xpathNodeList->item(0)->getAttribute('content');
}

【讨论】:

  • 谢谢,我会试试的。 ^^
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-23
  • 2013-08-11
  • 1970-01-01
  • 1970-01-01
  • 2013-08-21
  • 1970-01-01
相关资源
最近更新 更多