A
A
ademar262016-08-04 15:45:02
PHP
ademar26, 2016-08-04 15:45:02

Why might the parsing script not work?

There is a script code. It parses the pictures as it should and writes them to the sql file. But it is necessary that the description and article of the product be written to the file. But here's the problem, for some reason he writes to the file not the article but the name of the product, although the code contains the condition through the switch to search in the tag - tr through the array by the keyword of the word. What could be the problem????? Thanks in advance.

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
</head>
</html>
<?php

include_once('curl/curl_query.php');
define('_DS_', DIRECTORY_SEPARATOR);
class tdm_parse
{

    private $link = "http://tdme.ru";
    //public $path = __DIR__ . _DS_ . "catalog" . _DS_;
     // private $SHD_path = include('../shd/simple_html_dom.php');
    //private $PHPExcel_path = __DIR__ . 'PHPExcel' . __DIR__ . 'PHPExcel.php' ;
    /**
     * @param $SHD_path - path to library simple html dom
     * @return array|int - array of categories
     */
    private function get_categories(){

        //Получаем список категорий из сайдбара
        $html = new simple_html_dom();
    //$html = file_get_html('http://tdme.ru/product/');
        //$html = str_get_html($html);
       $html = curl_get('http://tdme.ru/product/');
       $html = str_get_html($html);
        if($categories = $html->find('div.sidebar ul.submenu')[1]->children){
           //sleep(2);
           $parsed_category = array();
           foreach ($categories as $category){
                $parsed_category[] = $category->outertext;
            }
            return $parsed_category;
        }
    
        
    }

    /**
     * @param $categories
     * @return array
     */
    private function get_models($categories){
        //Подгружаем каждую из полученных категорий и вытаскиваем впоследствии список моделей из каждой подкатегории
        $array_of_sub = array();

        $html = new simple_html_dom();
        if (isset($categories)){
        foreach ($categories as $category){
            $parent = new simple_html_dom();
            //Создаем два объекта для подгрузки из распарсенного и из сайта

            $parent->load($category);
            //Получаем ссылку подкатегории и загружаем её страницу
            $parent = $parent->find('a')[0]->href;
            $html = curl_get($this->link . $parent);
            $html = str_get_html($html);
            //Загружаем ссылки всех подкатегорий
            
            $subcategories = $html->find('ul.category')[0]->children;
            
         foreach ($subcategories as $sub) {
                $array_of_sub[] = $parent . $sub->find('a')[0]->href;
            }}
            return $array_of_sub;
        }}


    private function get_price($subcat){
        $sql_file = fopen('base.sql', 'a+');
    
        $path_to_images = __DIR__ . _DS_ ."catalog". _DS_ ;
        $manufacturer_id = 25;
        //Разбираем подкатегории на отдельные группы товаров
        //$table_of_goods - таблица товаров общая
        //$table_header, $table_body - заголовок и тело таблицы соответственно
        $table_of_goods = new simple_html_dom();
        
        $html_sub = file_get_html($this->link . $subcat);
       // $html_sub = str_get_html($html_sub);
        //var_dump(get_class($html_sub));
        $description = new simple_html_dom();
        //Получаем описание, полное для всех товаров (кроме характеристик)
        $description = $html_sub->find('dl.tabs')[0]->find('dd.selected')[0]->find('div.tab-content')[0];
     
        //$description = $html_sub->find('dl.tabs dd.selected div.tab-content')[0];
        $description = htmlspecialchars($description->plaintext);
         
    
     
        //echo "<HR>";
        
        $table_of_goods = $html_sub->find('div#modal_table table.mod_t')[0]->children;

        $table_header = $table_of_goods[0]->find('tr')[0];
        $table_body = $table_of_goods[1]->children;
        $numer = array();
        //Вытягиваем номера ячеек с необходимыми нам столбцами
        foreach (($table_header->children) as $num => $th_row) {
            //  echo "FIRST foreach<br>";
            //var_dump($th_row->plaintext);
            //var_dump($num);
            switch(trim($th_row->plaintext)){
                case 'Наименование':
               // case 'Наименование светильника':
                    $numer["name"] = $num;
                    break;
                case 'Фото':
                case 'Изображение':
                    $numer['image'] = $num;
                    break;
                case 'Артикул':
                    $numer['model'] = $num;
                    break;
            }

        }
        if (!(isset($numer['image']))){
            $numer['image'] = '-1';
            $image_path = $html_sub->find('div.product_info div.image div img')[0]->src;
        }
        //echo "<hr>";
        $rowspan = 1;
        //Вытягиваем изображение и информацию из ячеек данных

        foreach ($table_body as $table_line){
            // echo "second foreach<br>";
            //прогоняемся по всем элементам таблицы, вытаскиваем подкатегории 3 уровня и товары с их свойствами и картинками
            //var_dump($table_line->plaintext);
            $arr_of_tl = $table_line->children;
            if($rowspan == 1){
                $row_bool = 0;
            }
            else {
                $row_bool = 1;
                $rowspan--;
            }
            foreach ($arr_of_tl as $num => $value){
                //Сопоставляем ячейку с заголовком
                switch($num + $row_bool){

                    case $numer['image']: {
                        //Необходимо получить ячейку изображения и проверить его rowspan. записать его rowspan в отдельную переменную и если он не равен 1, то прибавлять +1 переменной num, чтобы
                        // не сбивался порядок ячеек в таблице при считывании данных.
                        if (isset($value->rowspan)) {
                            $rowspan = (int) $value->rowspan;
                            //var_dump($rowspan);
                        }
                        if (isset($value->find('img')[0])){
                            $image_path = $value->find('img')[0]->src;
              
              }//;
                            
                        //var_dump($image_path);
                        // $image = file_get_contents($image_path);
                        // file_put_contents($image["tmp_name"], $path_to_images);
                        //$image_addr = $path_to_images . $image;
                    }
                        break;
                    case $numer['model']: $article = $value->plaintext;
                        break;
                    case $numer['name']: $name = $value->plaintext;
                        break;

                }



            }
      if(isset($article) && $article !== '' && $article !== '  ')
      {
        $arr = explode("/", $image_path); 
                $imagen = end(str_replace(" ","",$arr));
        //file_put_contents(__DIR__ . _DS_ . "catalog" . _DS_ . $imagen, $this->link . $image_path);
        file_put_contents( 'catalog\\' . $imagen, file_get_contents('http://tdme.ru' . $image_path));
        
        //INSERT INTO base (name, image, description, article) VALUES ('6', '1st Street', 'Los Angeles', 'Harry Monroe')
           //$parsed_string = 'UPDATE tdm_upload SET `name` = \'' . $name . '\' `image` = \'catalog/'.   $article .   '\' `description` = \''.   $description .   '\' WHERE `article` = \'' . $article . "'; \n";
      $parsed_string = 'INSERT INTO base (image, description, article) VALUES (\'catalog\\'.$imagen.'\', \''. $description .'\', \''.$article."'); \n";
            fwrite($sql_file, iconv("WINDOWS-1251", "UTF-8", "$parsed_string") ); 
      
        
      }
      
        }
        $html_sub->clear();

        unset($html_sub);
        unset($table_of_goods);
        //$description->clear();
        //unset($description);
        return 1;
    }

    public function insert_into_mysql() {

        $this::Load(__DIR__ . '\shd\simple_html_dom.php');
        $categories = new simple_html_dom();
        $categories = $this->get_categories();
        $subcat = $this->get_models($categories);
        if(count($subcat)){
        foreach ($subcat as $models){
            sleep(1);
            $this->get_price($models);
        }}
        
        var_dump(($subcat));
        return 1;
    }
    public static function Load($pClassName){
        if ((class_exists($pClassName,FALSE))) {
            return FALSE;
        }

        if ((file_exists($pClassName) === FALSE) || (is_readable($pClassName) === FALSE)) {
            //    Can't load
            return FALSE;
        }

        require_once($pClassName);
    }   //    function Load()

}

$tdm_parse = new tdm_parse();
$tdm_parse->insert_into_mysql();
?>

Answer the question

In order to leave comments, you need to log in

3 answer(s)
X
xmoonlight, 2016-08-04
@xmoonlight

He must search correctly, but write and read - check!

S
Saboteur, 2016-08-04
@saboteur_kiev

And you manually check the file (HTML), maybe they just have a broken sign there, somewhere some kind of colspan or something like that.
PS They also have an illustrated excel - maybe it will be easier to parse it?
update:
add debug

switch(trim($th_row->plaintext)){
                case 'Наименование':
               // case 'Наименование светильника':
                    $numer["name"] = $num;
                    break;
                case 'Фото':
                case 'Изображение':
                    $numer['image'] = $num;
                    break;
                case 'Артикул':
                    $numer['model'] = $num;
                    break;
            }

for example, add the output here, what exactly for $num gets into $numer['model']
By the way, quotes are different in name and others.

O
Optimus, 2016-08-04
Pyan @marrk2

No one will disassemble your footcloth of code here to find a small bug. There you need to debug on the server specifically in stages.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question