文档文档如何获取信息和图像


domdocument how to get info and imgs

<?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;
}
?>

我得到了所有图像,但是如何获取有关图像所在元素的信息? 例如,在 amazon.com 上,有一个Kindle。我现在有图片,但需要周围的信息,例如价格描述......谢谢

这取决于所请求页面的标记,以下是在亚马逊上获取价格的示例:

<?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。如果没有,他们不希望你抓住任何东西。以这种方式解析是不可靠的,请求页面的标记每秒都会更改(您也可以为漏洞利用打开一扇门(。也可能不合法.