【问题标题】:domdocument how to get info and imgsdomdocument如何获取信息和imgs
【发布时间】:2011-05-24 19:26:58
【问题描述】:
<?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。我现在有图片,但需要价格说明等信息... 谢谢

【问题讨论】:

  • 如果你特别指的是大的kindle-image,那是没有办法的,因为你看到的价格是图片的一部分,在DOM内部是不可用的。 g-ecx.images-amazon.com/images/G/01/kindle/merch/…
  • 所以,跳过这个并浏览所有其他图像,包括这个..然后我就可以筛选那些在同一元素中没有任何信息的图像。
  • 为什么要对网站进行屏幕截图而不是使用 Amazon API?
  • amazon 是一个示例网站..我会刮别人的...所以我只想知道如何获取图像周围的所有信息..
  • 好吧,我们不能为虚构的网站编写任何代码。如果你想这么刮,请使用 API。如果您想抓取另一个站点并遇到问题,请更新您的问题以询问该特定站点。如果您只是在寻找有关如何使用 DOM 的示例,请浏览可用的示例。

标签: php html dom document


【解决方案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。如果不是,他们不想让你抢任何东西。以这种方式解析是不可靠的,所请求页面的标记可以每秒更改一次(您也可能为漏洞打开一扇门)。它也可能不合法。

【讨论】:

  • 谢谢。但亚马逊就是一个例子..我希望它能够废弃任何网站并首先检索图像,然后图像所在元素中的任何数据..可以是包含图像的 div。价格。描述等。
  • 所以你必须使用DOMDocument::crystalBall($htmlget,guessWhatIWant)
  • 哈哈.. 基本上,我想抓取任何 url,获取图像并以某种方式获取包含在其自身元素中的任何信息.. 它可能是一个 div 。例如
    blah blah
  • PHP 或 DOM 中没有“不知何故”。只要没有标准规定图像必须拥有包含更多信息的包装器,您就无法以独特的方式处理任何 url。
  • 但如果没有自己的包装器,它应该显示,如果确实如此,那么在包装器中显示任何东西..我不介意。一旦我有了这个,我将完成我在包装器中获得的信息所需的其余部分
猜你喜欢
  • 1970-01-01
  • 2023-04-02
  • 2021-10-07
  • 2014-02-11
  • 2010-10-20
  • 2012-05-18
  • 1970-01-01
相关资源
最近更新 更多