使用 Xpath 进行网页抓取,抓取 img
Web scraping with Xpath, grabbing img
我正在尝试从页面中抓取一些 img。但不能抓住那些。我的路径是正确的(我认为)但是 Xpath returns 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()
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);
我正在尝试从页面中抓取一些 img。但不能抓住那些。我的路径是正确的(我认为)但是 Xpath returns 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()
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);