PHP HTML DOM Parser Amazon предлагает список всех цен и имен продавцов - PullRequest
1 голос
/ 14 октября 2011

Я пытаюсь узнать цену и продавца на страницах со списком предложений Amazon, найденных по адресу:

http://www.amazon.com/gp/offer-listing/B002UYSHMM

. Я могу получить цену, используя:

$ret['Retail'] = $html->find('span[class="price"]', 0)->innertext;

Это перетягивает первую цену в списке предложений

Я пытался вытащить соответствующего продавца по первой цене, используя нижеприведенное, чтобы получить значение alt из img, которое содержит имя продавца:

$ret['SoldBy'] = $html->find('ul.sellerInformation img', 0)->getAttribute('alt');

Первый сработал, но когда я пошёл вниз, в некоторых случаях стали пропадать продавцы и даже отсутствовали цены.

Может кто-нибудь сказать, почему он пропустит продавцов и даже скачет по ценам?Все, что я сделал, чтобы получить дополнительных продавцов:

$ret['Retail2'] = $html->find('span[class="price"]', 1)->innertext;
$ret['SoldBy2'] = $html->find('ul.sellerInformation img', 1)->getAttribute('alt');
$ret['Retail3'] = $html->find('span[class="price"]', 2)->innertext;
$ret['SoldBy3'] = $html->find('ul.sellerInformation img', 2)->getAttribute('alt');
$ret['Retail4'] = $html->find('span[class="price"]', 3)->innertext;
$ret['SoldBy4'] = $html->find('ul.sellerInformation img', 3)->getAttribute('alt');
$ret['Retail5'] = $html->find('span[class="price"]', 4)->innertext;
$ret['SoldBy5'] = $html->find('ul.sellerInformation img', 4)->getAttribute('alt');
$ret['Retail6'] = $html->find('span[class="price"]', 5)->innertext;
$ret['SoldBy6'] = $html->find('ul.sellerInformation img', 5)->getAttribute('alt');
$ret['Retail7'] = $html->find('span[class="price"]', 6)->innertext;
$ret['SoldBy7'] = $html->find('ul.sellerInformation img', 6)->getAttribute('alt');

Спасибо за любые предложения!

Ответы [ 2 ]

1 голос
/ 11 ноября 2011

Я использовал foreach и помещал результаты в массив.Работал намного лучше, так как количество продавцов варьируется от пункта.

1 голос
/ 26 октября 2011
<?php

$url = 'http://www.amazon.com/gp/offer-listing/B0036RNK7O/ref=dp_olp_new?ie=UTF8&qid=1319582305&sr=8-2';

$dom = new DomDocument();

$content = file_get_contents($url);
$dom->loadHTML($content);

$results = array();
$classes_to_collect = array('price', 'shipping_block', 'condition', 'sellerInformation');
$seller_elements = array('name', 'rating', 'stock_info', 'item_info');

foreach($dom->getElementsByTagName('tbody') as $tb)
{
  if($tb->hasAttribute('class') && stripos($tb->getAttribute('class'), 'result')!==false)
  {
    foreach($tb->getElementsByTagName('tr') as $tr)
    {
      $new_result = array();
      foreach($tr->getElementsByTagName('td') as $td)
      {
        foreach($td->childNodes as $cne)
        {
          foreach($classes_to_collect as $ctc)
          {
            if($cne->hasAttributes() && $cne->getAttribute('class') && stripos($cne->getAttribute('class'), $ctc)!==false)
            {
              if($cne->localName=='ul')
              {
                $new_sellern = array();
                $lis = $cne->getElementsByTagName('li');
                foreach($lis as $lii=>$lie)
                {
                  $value = $lie->textContent;
                  if($seller_elements[$lii]=='item_info')
                  {
                    $cutoff = strpos($value, 'amznJQ.onReady');
                    if($cutoff) $value = substr($value, 0, $cutoff);
                  }
                  else if($seller_elements[$lii]=='name')
                  {
                    $cutoff = strpos($value, 'Seller:');
                    if($cutoff!==false) $value = substr($value, 7);
                  }
                  else if($seller_elements[$lii]=='rating')
                  {
                    $cutoff = strpos($value, 'Seller Rating:');
                    if($cutoff!==false) $value = substr($value, 14);
                  }
                  $new_seller[$seller_elements[$lii]] = trim($value);
                }
                $new_result[$ctc] = $new_seller;
              }
              else $new_result[$ctc] = $cne->textContent;
            }
          }
        }
      }
      $results[] = $new_result;
    }
  }
}

print_r($results);

Распечатает огромный многомерный массив

...