用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);

您正在查找div[@class='p-articlelist-content-img']而不是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);

最新更新