我正在尝试维护一些PHP代码,以进行网页抓取。网页已更改,因此需要进行更新,但是我对Xpath的了解并不丰富,因此很努力。
基本上,这是html的相关部分
<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>
我正在尝试从IMG标签提取srcset属性,该属性是“ /medias/myimage.jpg”的值。我正在使用XPATH Helper chrome插件来帮助我,我有以下xpath;
//div[@class="carousel-item-wrapper"]/picture/img/@srcset
在插件中,它返回的是我期望的值,因此它似乎可以正常工作。
如果我还使用在线xpath测试仪http://www.online-toolz.com/tools/xpath-editor.php,那么它也可以正常运行。
但是在我的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!
我当然已经尝试了很多不同的变化,试图不指定属性名称等。但是所有这些都没有运气。
我究竟做错了什么?我敢肯定它一定很简单,但是我看不到它。
在同一HTML文档上使用我的PHP代码的其他摘录也可以正常工作。因此,这就是造成我麻烦的因素。
PHP的DOMXPath类似乎在使用自闭合标签时遇到了麻烦。如果要查找自动关闭标签,则需要添加双斜杠,因此新的xPath查询应为:
//div[@class="carousel-item-wrapper"]/picture//img/@srcset
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句