@Inter_GLADOS

Как соеденить 2 функции в нужной последовательности чтобы скрипт выгружал фото товаров? И почему не выполняется условия ограничения выгрузки 100шт?

Здраствуйте можете помочь разобрать понять как изменить логику скрипта или добавить в него еще одну функцию парсинга фотографий с сайта донора. ДЛя самого парсинга информации нужные классы элементы используется скрипта:

<?php
    
    global $postCount;
    include_once 'db.php';
    include_once 'simple_html_dom.php';
    
    function curlGetPage($url, $referer = '
    https://google.com/')
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36');
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, 0);
    
        $response = curl_exec($ch);
        return $response;
    
    }
    
    function parseAndInsertData($html)
    {
        global $db;
    
        foreach ($html->find('*[class="col-6 col-lg-4 col-xl-3 us-item"]') as $element) {
            $img = $element->find('*[class="img-fluid oct-lazy"]',0);
            $link = $element->find('.us-module-img a', 0);
            $priceElem = $element->find('*[class="us-module-price-actual"]',0);
    
    
    
            $price = $priceElem->plaintext;
            $trimmedP = ltrim($price, "$");
    
    
           // $priceJIS = float($price);
            $post = [
                'img' => $img->src,
                'title' => $img->alt,
                'link' => $link->href,
                'price' => $trimmedP,
            ];
    
            $priceN = isset($post['price']) ? floatval($post['price']) : 0;
    
            $priceCH = floatval($price);
            $db->query("INSERT IGNORE INTO posts (`title`, `img`, `link`, `price`) 
            VALUES('{$post['title']}', '{$post['img']}', '{$post['link']}', {$priceN})");
    
            echo "Step cycle:" . PHP_EOL. $postCount;
    
            $price = $priceElem->plaintext;
            echo "Original price: " . $price . PHP_EOL;
    
            //$priceCH = floatval($price);
            echo "Parsed price: " . $priceN . PHP_EOL;
    
        }
    }
    
    //$page = curlGetPage('https://***/zaryadni-prystroyi');
    //$html = str_get_html($page);
    
    $url = 'https://***/zaryadni-prystroyi?page=1';
    $page = curlGetPage($url);
    $html = str_get_html($page);
    
    // Parse and insert data from the first page
    parseAndInsertData($html);
    
    $pagenavi = $html->find('ul.pagination',0);
    //$lastPageLink = $pagenavi[0]->lastChild();
    $lastLi = $pagenavi->find('li', -1);
    $lastAnchor = $lastLi->find('a', 0);
    
    if ($lastAnchor && $lastAnchor->hasAttribute('href')) {
        // Get the value of the "href" attribute and extract the page number (assuming it's the last part of the URL)
        $lastHref = $lastAnchor->getAttribute('href');
        $pageNumber = intval(basename($lastHref));
        $schetchik = $pageNumber + 1;
    
        // Output the parsed page number as an integer
       // echo "Last page number: " . $pageNumber;
    
        for ($i = 1; $i >= $schetchik ; $i++) {
            // Set the correct referer for pagination
    
    
            $referer = "https://optitrade.dp.ua/zaryadni-prystroyi/?page=$i";
    
            // Fetch the page content
            $page = curlGetPage($referer, $referer);
            $html = str_get_html($page);
    
            // Parse and insert data from the current page
            parseAndInsertData($html);
    
            usleep(1500000);
    
            // Optionally, you can add a limit to the number of pages to parse
            if ($i > 100) {
                break;
            }
        }
    }
    else{echo "Last link not found or doesn't have the 'href' attribute.";}
    ?>


Дальше есть скрипт с необходимой функцией, которую по логике нужно обьявить гдето в блоке после использования Курла. Но немогу понять почему сам парсер выгружает в мою базу все записи с сайта донора когда у меня поидее должно отрабатыватся условие помощью ( это второй мой вопрос но он не важный.
if ($i > 100) {
break;
}

Мой вопрос состоит в слудующем как ниженаписанную функцию внедрить правильно в вышестоящий код чтобы не изменлись содержание обьектов и переменных и чтобы парсрер не перестал отрабатываться.

<?php
        include_once 'simple_html_dom.php';
        
        function parseImagesWithClass($url, $targetClass, $localDirectory) {
            $html = file_get_html($url);
        
            if ($html !== false) {
                $elements = $html->find($targetClass);
        
                if (!is_dir($localDirectory)) {
                    mkdir($localDirectory, 0777, true);
                }
        
                foreach ($elements as $element) {
                    $imgElement = $element->find('img', 0);
                    if ($imgElement) {
                        $imgSrc = $imgElement->src;
        
                        // Ensure the image URL is absolute
                        if (strpos($imgSrc, 'http') === false) {
                            $imgSrc = $url . $imgSrc;
                        }
        
                        $imgFilename = $localDirectory . '/' . basename($imgSrc);
        
                        // Download the image and save it to the local directory
                        file_put_contents($imgFilename, file_get_contents($imgSrc));
                    }
                }
        
                $html->clear();
                unset($html);
            } else {
                echo "Failed to fetch HTML from the URL: $url";
            }
        }
    
        // Sample usage:
        $url = 'https://example.com/products'; // Replace with the URL of the product page
        $targetClass = '.product-image'; // Replace with the class that contains the product images
        $localDirectory = 'images'; // Replace with the local directory where images will be saved
        parseImagesWithClass($url, $targetClass, $localDirectory);
        ?>


Я так понимаю что по логике эту функцию parseImagesWithClass вторую нужно вызывать после parseAndInsertData($html) чтобы везде сохранились доступы к обьектам и они не перепутали друг друг содержимое.
Извените за столь сложный вопрос.
  • Вопрос задан
  • 67 просмотров
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы
01 мая 2024, в 09:23
5000 руб./за проект
01 мая 2024, в 02:11
5000 руб./за проект
01 мая 2024, в 00:29
2000 руб./за проект