Php Xpath查询返回NULL
我试图维护一些PHP代码,这是做网页抓取。网页已更改,因此需要更新,但我对Xpath没有太多经验,所以我很挣扎 基本上这是html的相关部分Php Xpath查询返回NULL,php,html,xpath,Php,Html,Xpath,我试图维护一些PHP代码,这是做网页抓取。网页已更改,因此需要更新,但我对Xpath没有太多经验,所以我很挣扎 基本上这是html的相关部分 <div class="carousel-item-wrapper"> <picture class=""> <source srcset="/medias/tea-tree-skin-clearing-foaming-cleanser-1-640x640.jpg?context=product-ima
<div class="carousel-item-wrapper">
<picture class="">
<source srcset="/medias/tea-tree-skin-clearing-foaming-cleanser-1-640x640.jpg?context=product-images/h3b/hd3/8796813918238/tea-tree-skin-clearing-foaming-cleanser_1-640x640.jpg" media="(min-width: 641px) and (max-width: 1024)">
<source srcset="/medias/tea-tree-skin-clearing-foaming-cleanser-1-320x320.jpg?context=product-images/h09/h9a/8796814049310/tea-tree-skin-clearing-foaming-cleanser_1-320x320.jpg" media="(max-width: 640px)">
<img srcset="/medias/myimage.jpg" alt="150 ML" class="">
</picture>
</div>
在插件中,它返回的结果与我期望的完全一致,因此它似乎工作正常
如果我也使用在线xpath测试仪,那么它也可以正常工作
但是在我的PHP代码中,我得到了一个空值
$dom = new DOMDocument();
$dom->preserveWhiteSpace = false;
$dom->strictErrorChecking = false;
$dom->recover = true;
@$dom->loadHtml($html);
$xPath = new DOMXPath($dom);
//Other xPath queries executed OK.
$node = $xPath->query('//div[@class="carousel-item-wrapper"]/picture/img/@srcset')->item(0);
if ($node === NULL)
writelog("Node is NULL"); // <-- Writes NULL to the log file!
$dom=newdomdocument();
$dom->preserveWhiteSpace=false;
$dom->strigerrorchecking=false;
$dom->recover=true;
@$dom->loadHtml($html);
$xPath=newdomxpath($dom);
//其他xPath查询执行正常。
$node=$xPath->query('//div[@class=“carousel item wrapper”]/picture/img/@srcset')->项(0);
如果($node==NULL)
writelog(“节点为空”);// PHP的DOMXPath类似乎在使用自动关闭标记时遇到问题。如果要查找自动关闭标记,则需要添加双正斜杠,因此新的xPath查询应为:
//div[@class=“carousel item wrapper”]/picture//img/@srcset
您使用哪个PHP类来读取/编辑/查询您的HTML数据?您可以添加一些详细信息吗?如何实例化$xPath等?您的HTML无效,请删除“loadHtml”之前的“@”,您将看到错误“Tag source invalid in Entity”。如果您可以编辑html,那么应该为源标记添加自动关闭标记@$dom->loadHtml($html)
<删除抑制错误的@
,这样您就不知道是否失败了-这可能是因为您的HTML无效。@christophe ninja'd:p成功了。非常感谢,我从来没有发现过!为了让其他人受益:XPath可以很好地处理自动关闭标记。这里所描述的似乎是针对所使用的特定XPath处理器中的错误的解决方法。
$dom = new DOMDocument();
$dom->preserveWhiteSpace = false;
$dom->strictErrorChecking = false;
$dom->recover = true;
@$dom->loadHtml($html);
$xPath = new DOMXPath($dom);
//Other xPath queries executed OK.
$node = $xPath->query('//div[@class="carousel-item-wrapper"]/picture/img/@srcset')->item(0);
if ($node === NULL)
writelog("Node is NULL"); // <-- Writes NULL to the log file!