php - 用 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);
解决方案
您正在寻找 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);
推荐阅读
- jaxb - com.sun.org.apache.xerces.internal.impl.XMLStreamReaderImpl 的 Java 11 UTF-16 BOM 问题
- node.js - 发布产品时发送推送通知
- python - 如何更新 pytest-html 中的环境表
- java - 错误:与元素类型“FrameLayout”关联的属性“xmlns:tools”的值不能包含“<”字符
- asp.net-core - “使用范围服务时,将服务注入 Invoke 或 InvokeAsync”是什么意思?
- python - Pythonic 代码将 3 位数字转换为所有可能的字母组合
- python-3.x - 显示网格搜索属性,因为它们不是该方法的一部分
- ios - Swift IPv4 和 IPv6 地址蜂窝数据
- java - Webview 卡在加载网站或 cloudfare 检查
- dart - flutter - bloc - 我如何在我的 Ui 中使用 FutureBuilder 来正确实现 Bloc 架构