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

标签 php facebook xpath html-parsing scrape

我正在做的事情与 Tweet 按钮或 Facebook 分享/点赞按钮所做的本质上是一样的,那就是抓取页面和最相关的数据片段标题。我能想到的最好的例子是当你在一个有很多文章的网站的首页上,你点击了一个 Facebook Like 按钮。然后它将获得与(最近的)“赞”按钮相关的帖子的正确信息。有些网站有 Open Graph 标签,但有些没有,但它仍然有效。

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

想法:

  • 找到图像的“容器”,然后使用第一个文本 block 。
  • 在包含特定类别(“描述”、“标题”)或元素(h1、h2、h3、h4)的元素中查找文本 block 。

标题备份:

  • 使用开放图标签
  • 仅使用 <title>
  • 仅使用 ALT 标签
  • 使用 META 标签

总结:提取图像不是问题,问题在于如何为它们获取相关标题。

问题:您将如何为每张图片获取相关的标题?也许使用 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 示例(函数 ported from my framework ):

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

关于php - 使用 XPath 远程抓取页面并获取最相关的图像标题或描述,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10667836/

相关文章:

javascript - 如何在 vuejs 组件中使用 laravel csrf token

php - Laravel 中的 JSON 给出错误 SQLSTATE[42000] : check the manual that corresponds to your MariaDB server

android - Cordova 应用程序的 read_stream

facebook - OpenGraph Watch Action 不出现在任何地方

python - 使用Scrapy爬取本地XML文件-起始URL 本地文件地址

regex - 无法从网址获取其他项目

php - 关于 SQL 查询中的分组结果

javascript - WordPress - fatal error : "Call to a member function get_var() on a non-object" but only if not as Template

iOS - 简单的 Facebook 身份验证

python - Scrapy 只在循环中返回第一个结果