【问题标题】:Web scraping with Xpath, grabbing img用 Xpath 抓取网页,抓取 img
【发布时间】:2018-11-05 02:30:57
【问题描述】:

我正在尝试从页面中抓取一些 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);

【问题讨论】:

  • 如果您在 foreach 循环上方执行 var_dump( $images )dd( $images ) 会发生什么?如果这对您没有任何帮助,那么也许可以尝试简化您的表达方式。例如:$rota->query("//section") - 看看这是否给你一些有用的东西。
  • 它什么也没给我。 @Zeth
  • 在 HTML 源代码中,您在哪里可以看到带有 p-articlelist-content-img 类的 div

标签: php html xpath domdocument


【解决方案1】:

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

除此之外,您不应使用 @ 运算符隐藏错误消息,而应按预期使用 libxml_use_internal_errors() function

最后,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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-06
    相关资源
    最近更新 更多