如何从其兄弟节点获取img的src和数据

问题描述 投票:0回答:1
<?php 
$htmlget = new DOMDocument();

@$htmlget->loadHtmlFile(http://www.amazon.com);

$xpath = new DOMXPath( $htmlget);
$nodelist = $xpath->query( "//img/@src" );

foreach ($nodelist as $images){
    $value = $images->nodeValue;
}
?>

我获得了所有 img 标签,但是如何获取图像所在同一元素的信息?

例如,在 amazon.com 上,有一个 kindle。我现在有图片,但需要它的相关信息,例如价格说明。

php html dom html-parsing siblings
1个回答
1
投票

这取决于请求页面的标记,这里是获取亚马逊价格的示例:

<?php
       $htmlget = new DOMDocument();

       @$htmlget->loadHtmlFile('http://www.amazon.com');

       $xpath = new DOMXPath( $htmlget);
       $nodelist = $xpath->query( "//img/@src" );

        foreach ($nodelist as $imageSrc){

      //fetch images with a parent node that has class "imagecontainer"
      if($imageSrc->parentNode->parentNode->getAttribute('class')=='imageContainer')
      {
        //skip dummy-images
        if(strstr($imageSrc->nodeValue,'transparent-pixel'))continue;

        //point to the common anchestor of image and product-details
        $wrapper=$imageSrc->parentNode->parentNode->parentNode->parentNode->parentNode;

        //fetch the price
        $price=$xpath->query( 'span[@class="red t14"]',$wrapper );
        if($price->length )
        {
           echo '<br/><img src="'.$imageSrc->nodeValue.'">'.$price->item(0)->nodeValue.'<br/>';
        };
      }
}
?>

但是,您不应该以这种方式解析页面。如果他们想向您提供一些信息,通常会有 API。如果没有,他们不想让你抢任何东西。这种解析方式并不可靠,所请求页面的标记每秒都可能发生变化(您也可能为漏洞利用打开一扇门)。它也可能不合法。

© www.soinside.com 2019 - 2024. All rights reserved.