【问题标题】:Getting only ONE URL from a "data-srcset" attribute with PHP Simple HTML DOM使用 PHP Simple HTML DOM 从“data-srcset”属性中仅获取一个 URL
【发布时间】:2019-10-16 20:49:32
【问题描述】:

我正在尝试从外部网站抓取图像 URL,以用作我自己网站上图像元素中的 src 属性。

问题是,在外部网站上,图像 URL 嵌套在 图片元素,在源元素中,然后在不同大小的“data-srcset”属性中迭代。示例:

<picture><source data-srcset="https://imageurl.com 640w, https://imageurl.com 720w, https://imageurl.com 860w"></picture>

我可以使用 PHP Simple HTML DOM 的 find() 来定位特定元素并将其存储在变量中。这个变量称为 $imageselector。我可以通过为 data-srcset 创建一个变量来进一步定位实际属性:

$srcset = 'data-srcset';

我的最终输出如下所示:

<?php echo $imageselector->$srcset; ?>

然而,这会尝试打印属性内的所有内容(当然),这对我来说不是很有用。

有没有人知道如何只获取属性中的第一个 URL?

(添加最大长度也没有多大用处,因为 URL 的长度随时可能发生变化)

【问题讨论】:

    标签: php html web-scraping attributes simple-html-dom


    【解决方案1】:

    您可以使用$imageselector-&gt;$srcset,将其内容拆分为一个数组并根据需要进行过滤。

    $longString = $imageselector->$srcset;
    $pics = explode(",", $longString)
    

    现在您有了一个包含 "https://imageurl.com 640w" 等内容的数组,所以现在您可以以 [1] 为例。

    $toUse = explode(" ", $pics[1]);
    $toUse = $toUse[0]; //to get the useful part of the item
    

    或者,您也可以对整个数组进行预过滤

    function getLink($string) {
        return substr($string, 0, strpos($string, " "));
    }
    //Once you already have the exploded string
    $pics = array_filter($pics, "getLink");
    

    【讨论】:

    • ..explode.. 不错。优雅而简单,谢谢!
    猜你喜欢
    • 2015-08-27
    • 2014-10-26
    • 2016-04-21
    • 1970-01-01
    • 2019-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多