如何使用xpath获取ul中所有图像的src?

我需要找到所有属于这个 ul 图像的 src,为此,我正在使用 xpath 来完成这项工作,但是它只返回第一个映像的 src。该如何获得所有 src? 下面是我的 HTML 结构。

<ul id="product-slider">
  <li >
    <img src="1.jpg" width="310" height="363" />
  </li>
  <li>
    <img src="2.jpg" style="opacity: 1;">
 </li>
 <li>
    <img  width="310" height="363" src="3.jpg">
 </li>      
</ul>

下面是我的代码片段:

$img = $xpath->query("//ul[@id='product-slider']//img/@src");
foreach($img as $i){
  echo $i->nodeValue;
}

它找不到所有图像的 src,除了第一个。有人能提供一些帮助吗?

看看这个http://codepad.viper-7.com/RiiFfK

To get a list of all images (actually, all the values from the src attributes) inside this ul, in your case, you can use XPath Axes:

//ul[@id='product-slider']/descendant::img/@src

What this does is:

  1. /ul[@id='product-slider'] selects the ul element with id='product-seller'

  2. /descendant::img selects all the descendants (children, grandchildren, etc.) from the ul

  3. /@src selects the src attribute of each one of these descendants.

XPath Axes is a great tool, you can find more information about it in here: http://www.w3schools.com/xpath/xpath_axes.asp (I know they're not the most relliable source for everything, but this XPath tutorial is quite a good intro).

Edit: Using OP's new code snippet from codepad as an example: The captured element inside the source code from Snapdeal Link is the following ul, in which only the first img tag contains a src attribute.

    <ul id="product-slider" class="mainImageSlider">
        <li>
            <img title="Apple iPhone 5S 16 GB (Gold)"  class="jqzoom zoomPad lazyBg" itemprop="image"  src="http://n2.sdlcdn.com/imgs/a/j/x/large/Apple-iPhone-5S-16-GB-SDL218153659-1-d5617.jpg" width="310" height="363" alt="Apple iPhone 5S 16 GB (Gold)" bigimage="http://n4.sdlcdn.com/imgs/a/j/x/Apple-iPhone-5S-16-GB-SDL218153659-1-d5617.jpg">
        </li>
        <li>
            <img title="Apple iPhone 5S 16 GB (Gold)"  class="jqzoom zoomPad lazyBg"  lazySrc="http://n1.sdlcdn.com/imgs/a/j/x/large/Apple-iPhone-5S-16-GB-SDL218153659-2-af89e.jpg" width="310" height="363" alt="Apple iPhone 5S 16 GB (Gold)" bigimage="http://n1.sdlcdn.com/imgs/a/j/x/Apple-iPhone-5S-16-GB-SDL218153659-2-af89e.jpg">
        </li>
        <li>
            <img title="Apple iPhone 5S 16 GB (Gold)"  class="jqzoom zoomPad lazyBg"  lazySrc="http://n4.sdlcdn.com/imgs/a/p/0/large/Apple-iPhone-5S-16-GB-SDL218153659-3-14019.jpg" width="310" height="363" alt="Apple iPhone 5S 16 GB (Gold)" bigimage="http://n4.sdlcdn.com/imgs/a/p/0/Apple-iPhone-5S-16-GB-SDL218153659-3-14019.jpg">
        </li>
        <li>
            <img title="Apple iPhone 5S 16 GB (Gold)"  class="jqzoom zoomPad lazyBg"  lazySrc="http://n4.sdlcdn.com/imgs/a/p/0/large/Apple-iPhone-5S-16-GB-SDL218153659-4-fa8f3.jpg" width="310" height="363" alt="Apple iPhone 5S 16 GB (Gold)" bigimage="http://n4.sdlcdn.com/imgs/a/p/0/Apple-iPhone-5S-16-GB-SDL218153659-4-fa8f3.jpg">
        </li>
    </ul>

</div>