使用 XPath 远程抓取页面并获取最相关的图像标题或描述


Remotely Scrape Page and Get most Relevant title or Description for Images with XPath

我正在做的事情本质上与推文按钮或Facebook分享/喜欢按钮所做的相同,那就是抓取页面和最相关的标题。我能想到的最好的例子是,当你在一个包含许多文章的网站的首页上,你点击了一个Facebook的"喜欢"按钮。然后,它将获得相对于(最近("赞"按钮的帖子的正确信息。有些网站有 Open Graph 标签,但有些没有,它仍然有效。

由于这是远程完成的,因此我只能控制要定位的数据。在本例中,数据是图像。我不是只检索页面的<title>,而是希望以某种方式从每个图像的起点反向遍历 dom,并找到最近的"标题"。问题是并非所有标题都出现在图像之前。但是,在这种情况下,图像出现在标题之后的可能性似乎相当高。话虽如此,我希望让它几乎适用于任何网站。

思潮:

  • 找到图像的"容器",然后使用第一个文本块。
  • 在包含某些类("描述"、"标题"(或元素(h1,h2,h3,h4(的元素中查找文本块。

标题备份:

  • 使用开放图形标记
  • 仅使用<title>
  • 仅使用 ALT 标记
  • 使用元标记

摘要:提取图像不是问题,而是如何为它们获取相关标题。

问题:您将如何获得每个图像的相关标题?也许使用DomDocument或XPath?

您的方法似乎足够好,我只会给某些标签/属性一个权重,并使用 XPath 查询遍历它们,直到我找到退出的东西并且它不是无效的。像这样:

i = 0
while (//img[i][@src])
  if (//img[i][@alt])
    return alt
  else if (//img[i][@description])
    return description
  else if (//img[i]/../p[0])
    return p
  else
    return (//title)
  i++

一个简单的 XPath 示例(从我的框架移植的函数(:

function ph_DOM($html, $xpath = null)
{
    if (is_object($html) === true)
    {
        if (isset($xpath) === true)
        {
            $html = $html->xpath($xpath);
        }
        return $html;
    }
    else if (is_string($html) === true)
    {
        $dom = new DOMDocument();
        if (libxml_use_internal_errors(true) === true)
        {
            libxml_clear_errors();
        }
        if ($dom->loadHTML(ph()->Text->Unicode->mb_html_entities($html)) === true)
        {
            return ph_DOM(simplexml_import_dom($dom), $xpath);
        }
    }
    return false;
}

而实际使用情况:

$html = file_get_contents('http://en.wikipedia.org/wiki/Photography');
print_r(ph_DOM($html, '//img')); // gets all images
print_r(ph_DOM($html, '//img[@src]')); // gets all images that have a src
print_r(ph_DOM($html, '//img[@src]/..')); // gets all images that have a src and their parent element
print_r(ph_DOM($html, '//img[@src]/../..')); // and so on...
print_r(ph_DOM($html, '//title')); // get the title of the page