首页 > 解决方案 > 用 Xpath 抓取网页,抓取 img

问题描述

我正在尝试从页面中抓取一些 img。却抓不住那些。我的路径是真的(我认为)但 Xpath 返回 0。知道我的路径有什么问题吗?

function pageContent($url)
{

    $html = cache()->rememberForever($url, function () use ($url) {
        return file_get_contents($url);
    });

    $parser = new \DOMDocument();
    $parser->loadHTML($html);
    return $parser;

}

$url = 'https://sumai.tokyu-land.co.jp/osaka';

@$parser = pageContent($url);

$resimler = [];
$rota = new \DOMXPath($parser);
$images = $rota->query("//section//div[@class='p-articlelist-content-left']//div[@class='p-articlelist-content-img']//img");


foreach ($images as $image) {
    $resimler[] = $image->getAttribute("src");
}

var_dump($resimler);

标签: phphtmlxpathdomdocument

解决方案


您正在寻找 adiv[@class='p-articlelist-content-img']而不是 a ul

除此之外,您不应向操作员隐藏错误消息,而应按预期@使用该libxml_use_internal_errors()功能。

最后,//XPath 中的搜索成本很高,所以尽可能避免使用它,并且可以直接从查询中获取属性值(不过我不知道这是否更有效。)

function pageContent(String $url) : \DOMDocument
{
    $html = cache()->rememberForever($url, function () use ($url) {
        return file_get_contents($url);
    });
    $parser = new \DOMDocument();
    libxml_use_internal_errors(true);
    $parser->loadHTML($html);
    libxml_use_internal_errors(false);
    return $parser;
}

$url    = "https://sumai.tokyu-land.co.jp/osaka";
$parser = pageContent($url);
$rota   = new \DOMXPath($parser);
$images = $rota->query("//ul[@class='p-articlelist-content-img']/li/img/@src");

foreach ($images as $image) {
    $resimler[] = $image->nodeValue;
}

var_dump($resimler);

推荐阅读