PHP code example of icy8 / web-spider

1. Go to this page and download the library: Download icy8/web-spider library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

icy8 / web-spider example snippets


    
    use icy8\WebSpider\selectors\Xpath;
    use icy8\WebSpider\Spider;

    include "../vendor/autoload.php";
    $config        = [
        'entry_link'        => ['https://www.xxx.com'],// 入口页面
        'content_link_rule' => [// 内容页链接规则
            '#^https://www\.xxx\.com/e/\d+/[a-zA-Z0-9]+\.shtml$#is',
        ],
        'list_link_rule'    => [// 列表页链接规则
            '#^https\://www\.xxx\.com/xiaoxue[/]*$#is',
            '#^https\://www\.xxx\.com/chuzhong[/]*$#is',
        ],
        'fields'            => [// 数据字段
            [
                'name'     => 'title',// 字段名
                'rule'     => '//h1[@class="h_title"]',// 匹配规则
                '           ],
        ],
    ];
    // 配置链接池,SplQueue容器不需要配置该项
    $spider->queueConfig = [
        'type'     => 'redis',// 如果有其他自定义的容器,这里填入类名即可
        'host'     => '127.0.0.1',
        'password' => '',
    ];
    
    //$spider->count = 30;// 启动30个进程并行采集
    //$spider->daemonize = true;// 守护进程运行
    $spider        = new Spider($config);
    $spider->on('onContentPage', function ($page, $data) {
        // 这里会得到匹配到的数据$data
        // 如果希望自己来匹配,这时候将fields数组留空即可,此时闭包的$data值是false
        // $page是Page类的实例,附带了内容页的完整html
    });
    $spider->run();
    


$rule = '//a/@href';
$html = '...';
// 取一条记录
$data = Xpath::shortcut()->setData($html)->fetch($rule);
// 获取多条记录,如果匹配成功将永远返回一个数组
$data = Xpath::shortcut()->setData($html)->select($rule);
// 如果你希望返回元素的html内容,比如规则//a,你希望返回<a>text</a>
$data = Xpath::shortcut()->setData($html)->select($rule, true);



namespace icy8\WebSpider\selectors;


interface Selector
{
    // 设置选择器的数据内容,如html
    public function setData($data);

    // 执行选择,返回Array
    public function select($rule);
    
    // 执行选择,返回一条记录
    public function fetch($rule);

    // 返回一个新的实例,即new static()
    public static function shortcut();
}

shell
    # start stop status
    # -d 守护进程运行
    php crawl.php start -d