用phpSpider爬虫采集糗事百科

爬虫技术PHP 732

今天发现了一个好玩的php爬虫框架phpSpider,这里写了个官方的demo,可以采集糗百的内容和作者并入库到MYSQL数据库中。

phpSpider官方文档:https://doc.phpspider.org/,需要注意的是:一定要在命令行下运行

先用mysql按照以下信息建立一个名为phpspider的数据库:

  • 表:content
  • 字段:id,body,author

核心文件 test.php

<?php
require_once __DIR__ . '/../autoloader.php';
use phpspider\core\phpspider;

/* Do NOT delete this comment */
/* 不要删除这段注释 */


$configs = array(
    'name' => '糗事百科',
    'domains' => array(
        'qiushibaike.com',
        'www.qiushibaike.com'
    ),
    'scan_urls' => array(
        'http://www.qiushibaike.com/'
    ),
    'content_url_regexes' => array(
        "http://www.qiushibaike.com/article/\d+"
    ),
    'list_url_regexes' => array(
        "http://www.qiushibaike.com/8hr/page/\d+\?s=\d+"
    ),
    'fields' => array(
        array(
            // 抽取内容页的文章内容
            'name' => "body",
            'selector' => "//*[@id='single-next-link']/div",
            'required' => true
        ),
        array(
            // 抽取内容页的文章作者
            'name' => "author",
            'selector' => "//div[contains(@class,'author')]//h2",
            'required' => true
        ),
    ),
    'export' => array(
        'type' => 'db', 
        'table' => 'content',
    ),       
    'db_config' => array(
        'host'  => '127.0.0.1',
        'port'  => 3306,
        'user'  => 'root', #数据库用户名
        'pass'  => 'root', #数据库密码
        'name'  => 'phpspider', #数据库名
    ),
 
);
$spider = new phpspider($configs);
$spider->start();

命令行下运行 php test.php即可执行采集工作。

有点有意思的事

/* Do NOT delete this comment */
/* 不要删除这段注释 */

无论如何,不管是新建项目还是在官方的examples里面改,都要带上这个注释,别怪我没提醒你。

Post Comment