【问题标题】:Scraping Links on Webpage Need to Determine if they contain Img elements网页抓取链接需要判断是否包含Img元素
【发布时间】:2015-06-15 15:54:22
【问题描述】:

我正在为一个项目构建一个自定义刮板。我目前可以抓取网页上的所有链接,将 HREF 和锚文本存储在数据库中。但是,在尝试确定锚元素是否包含图像元素时,我遇到了困难。

这是我的代码:

foreach($rows as $row) {
    $url = $row['url'];
    $dom = new DOMDocument;
    libxml_use_internal_errors(TRUE); //disable libxml errors
    $dom->loadHTML(file_get_contents($url));

    // Write source page, destination URL and anchor text to the database
    foreach($dom->getElementsByTagName('a') as $link) {
        $href = $link->getAttribute('href');
        $anchor = $link->nodeValue;
        $img = $link->getElementsByTagName('img');
        $imgalt = $img->getAttribute('alt');

然后我将数据写入数据库。这在 $img 和 $imgalt 中工作正常,但我真的想确定锚是否包含图像以及是否有 alt 属性。我知道问题是我如何尝试使用 getElementsByTagName 选择图像。我整天都在谷歌上搜索并尝试了很多不同的建议,但似乎没有任何效果。这甚至可能吗?

我已按照here 中提到的说明进行操作。

有一些进展。我可以在锚元素中回显图像的 HTML(如果我只是 echoDOMinnerHTML($link)),但我仍然无法获得 alt 属性。我不断收到“在非对象上调用成员函数 getAttribute()”。

这是我现在的代码:

foreach($dom->getElementsByTagName('a') as $link) {
        $href = $link->getAttribute('href');
        $anchor = $link->nodeValue;
        $imgdom = DOMinnerHTML($link);
        $imgalt = $imgdom->getAttribute('alt');
        if(isset($imgalt)){
            echo $imgalt;
        }

【问题讨论】:

  • 不清楚你在问什么。如果您可以在链接下获取图像,那么您可以确定该链接也包含图像。
  • 嗨@felipsmartins。如果我的问题不清楚,请道歉。基本上,我正在抓取网页上的所有链接,然后将 HREF 和锚文本存储到数据库中。但是,我还想检查是否有任何链接包含图像元素。它正在弄清楚他们是否有给我带来麻烦的图像元素。
  • 我认为@felipsmartins 的回答是正确的方法

标签: php dom domdocument getelementsbytagname getattribute


【解决方案1】:

好吧,我只是假设你想要这样的东西:

<?php

$html_fragment = <<<HTML
<html>
<head>
    <title></title>
</head>
<body>
<div id="container">
    <a href="#a">there is n image here</a>
    <a href="#b"><img src="path/to/image-b" alt="b: alt content"></a>
    <a href="#c"><img src="path-to-image-c"></a>
    <a href="#d"><img src="path-to-image-d" alt="c: alt content"></a>
</div>
</body>
</html>
HTML;


$dom = new DOMDocument();
@$dom->loadHTML($html_fragment);
$links = $dom->getElementsByTagName('a');

foreach ($links as $link) {
    # link contains image child?
    $imgs    = $link->getElementsByTagName('img');
    $has_img = $imgs->length > 0;

    if ($has_img) {     
        $has_alt = (bool) $imgs->item(0)->getAttribute("alt");
        # img element has alt attribute?
        if ($has_alt) {
            // do something...
        }
    } else {
        // do something...
    }
}

请记住,如 PHP 文档中所说,DOMElement::getAttribute() 返回属性的值,如果没有找到具有给定名称的属性,则返回 空字符串。所以为了检查节点属性是否存在,只需检查返回值是否为空字符串。

【讨论】:

  • 感谢您的解决方案。我真的只是在 30 秒前自己想通了!我会把你的标记为正确,因为它看起来比我的解决方案更干净:)
猜你喜欢
  • 2021-04-07
  • 2015-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-12
  • 2011-11-02
  • 2020-08-08
  • 1970-01-01
相关资源
最近更新 更多