iT邦幫忙

2023 iThome 鐵人賽

DAY 23
0
Software Development

開心撰寫 PHPUnit系列 第 23

Day 23. 使用 Generator 重構分頁 - 更快速得到回應

  • 分享至 

  • xImage
  •  

批踢踢實業坊›看板 Gossiping 這一頁來說將近 4萬頁的資訊,如果我們是照現有程式的做法會面臨到幾個問題

  • 看版及分頁過多會遇到記憶體不足
  • Exception 發生時,已分析的網頁會全部白癈

這兩個都是很頭痛的問題,因為一但發生這兩個問題,就代表著我們等待的時間都白白浪廢了啊,所以這時候我們就可以祭出 Generator,讓我們可以一頁一頁的將資料存入資料庫,所以我們就可以把程式碼改為

<?php

namespace Recca0120\Ithome30\Crawlers;

use Generator;
use GuzzleHttp\Psr7\Request;
use Recca0120\Ithome30\Paginator;
use Psr\Http\Client\ClientInterface;

class Board
{
    public function __construct(private ClientInterface $httpClient)
    {
    }

    public function fetch(array $board, ?int $take = null): Generator
    {
        $url = $board['url'];

        $page = 0;
        do {
            $page++;

            $html = $this->sendRequest($url);
            $rows = array_map(
                fn (string $row)  => $this->parseCols($row, $board),
                $this->parseRows($html)
            );
            // 改為 yield 即可
            yield $paginator = new Paginator($html, $rows, $page);

            if ($take !== null && $paginator->currentPage >= $take) {
                break;
            }

            $url = $paginator->meta['prev'];
        } while ($paginator->hasMorePage());
    }

    private function sendRequest($url)
    {
        $request = new Request('GET', $url, [
            'Accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8',
            'Accept-Encoding' => 'gzip, deflate, br',
            'Accept-Language' => 'zh-TW,zh;q=0.8',
            'Cache-Control' => 'max-age=0',
            'Cookie' => 'over18=1',
            'Referer' => 'https://www.ptt.cc/bbs/Gossiping/index.html',
            'Sec-Ch-Ua' => '"Brave";v="117", "Not;A=Brand";v="8", "Chromium";v="117"',
            'Sec-Ch-Ua-Mobile' => '?0',
            'Sec-Ch-Ua-Platform' => '"macOS"',
            'Sec-Fetch-Dest' => 'document',
            'Sec-Fetch-Mode' => 'navigate',
            'Sec-Fetch-Site' => 'same-origin',
            'Sec-Fetch-User' => '?1',
            'Sec-Gpc' => '1',
            'Upgrade-Insecure-Requests' => '1',
            'User-Agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36',
        ]);
        $response = $this->httpClient->sendRequest($request);
        $html = (string)$response->getBody();

        return $html;
    }

    private function parseCols($row, $board)
    {
        preg_match_all('/<div class="(?<name>(nrec|title|author|date))"[^>]*>(?<value>.*?)<\/div>/s', $row, $matches);

        $cols = [
            'board_name' => $board['name'],
            'board_class' => $board['class'],
        ];

        foreach (array_keys($matches[0]) as $index) {
            $cols[$matches['name'][$index]] = trim($matches['value'][$index]);
        }
        $cols['nrec'] = strip_tags($cols['nrec']);

        preg_match('/href="(.*)"/', $cols['title'], $matched);
        $cols['url'] = 'https://www.ptt.cc' . $matched[1];

        preg_match('/\[(.+)\](.+)/', strip_tags($cols['title']), $matched);
        $cols['type'] = trim($matched[1]);
        $cols['title'] = trim($matched[2]);

        return $cols;
    }

    private function parseRows($html)
    {
        preg_match_all('/class="r-ent">.+<div class="mark">(.+)<\/div>/sU', $html, $matches);

        return $matches[0];
    }
}

但這樣的調整測試不就壞了?這時測試也只需要修改一個地方就能綠燈了

<?php

namespace Recca0120\Ithome30\Tests\Crawlers;

use Mockery;
use GuzzleHttp\Client;
use PHPUnit\Framework\TestCase;
use Recca0120\Ithome30\Crawlers\Board;

class BoardTest extends TestCase
{
    public function test_fetch_board_articles_list()
    {
        \VCR\VCR::turnOn();
        \VCR\VCR::insertCassette('ptt_gossiping.yaml');

        /** @var Mockery\Mock|ClientInterface $httpClient */
        $httpClient = Mockery::spy(new Client());

        $crawler = new Board($httpClient);
        // 加入 iterator_to_array
        $records = iterator_to_array($crawler->fetch([
            'name' => 'Gossiping',
            "nuser" => '8803',
            'class' => '綜合',
            'title' => '[八卦] 亞運李智凱、許皓鋐奪金!',
            'url' => 'https://www.ptt.cc/bbs/Gossiping/index.html'
        ], 2));

        self::assertCount(23, $records[0]);
        self::assertEquals([
            'board_name' => 'Gossiping',
            'board_class' => '綜合',
            'nrec' => '4',
            'type' => '問卦',
            'title' => '司機夫人真的有去卡地亞血拚$1.1M嗎?',
            'author' => 'uwmtsa',
            'date' => '10/06',
            'url' => 'https://www.ptt.cc/bbs/Gossiping/M.1696537444.A.1A5.html',
        ], $records[0][0]);

        \VCR\VCR::eject();
        \VCR\VCR::turnOff();
    }
}

這樣我們就可以每爬完一次分頁就可以進行處置了,比較可以不必擔心資料白爬的情況發生了


上一篇
Day 22. 重構分頁 - 想知道分頁資訊怎麼辦
下一篇
Day 24. 判斷測試的種類 - 把測試移到合適的地方
系列文
開心撰寫 PHPUnit30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言