说到做爬虫,人人都能够第一时间想到的是python,实在php也是能够用来写爬虫顺序的。php一向简约、易用,亲测运用PHPspider框架10分钟就能够写出一个简朴的爬虫顺序。
一、PHP环境装置
和python一样,PHP也须要环境,能够运用官网下载的PHP,也能够运用XAMPP、PHPstudy等集成环境下的PHP。比较引荐集成环境,省去零丁装置Mysql数据库。
二、composer装置
composer是PHP下的依靠包管理工具,类似于Python中的PIP。
中文官网为https://www.phpcomposer.com/
下载装置即可,win+R运转cmd,输入composer敕令,涌现以下图所示申明装置胜利了。
三、PHPspider装置
在恣意位置竖立一个文件夹,比方我们要抓取简书的数据,我们能够在D盘竖立jianshu文件夹,然后cmd敕令进入该文件夹,运转敕令:
composer require owner888/phpspider
以下效果就是胜利装置了。
相干引荐:《php环境搭建》
四、最先写第一个爬虫
如今翻开jianshu文件夹,会发明内里多了一些东西,不必管它,竖立一个php文件,最先打代码。
开辟文档在这:https://doc.phpspider.org/demo-start.html
这边不讲基本,直接上代码,由于我们是做的10分钟疾速教程。
婚配体式格局运用XPach语法。
<?php require '/vendor/autoload.php'; use phpspider\core\phpspider; /* Do NOT delete this comment */ /* 不要删除这段解释 */ $configs = array( 'name' => '简书', 'log_show' =>false, 'tasknum' => 1, //数据库设置 'db_config' => array( 'host' => '127.0.0.1', 'port' => 3306, 'user' => 'root', 'pass' => '', 'name' => 'demo', ), 'export' => array( 'type' => 'db', 'table' => 'jianshu', // 假如数据表没有数据新增请检查表构造和字段名是不是婚配 ), //爬取的域名列表 'domains' => array( 'jianshu', 'www.jianshu.com' ), //抓取的出发点 'scan_urls' => array( 'https://www.jianshu.com/c/V2CqjW?utm_medium=index-collections&utm_source=desktop' ), //列表页实例 'list_url_regexes' => array( "https://www.jianshu.com/c/\d+" ), //内容页实例 // \d+ 指的是变量 'content_url_regexes' => array( "https://www.jianshu.com/p/\d+", ), 'max_try' => 5, 'fields' => array( array( 'name' => "title", 'selector' => "//h1[@class='title']", 'required' => true, ), array( 'name' => "content", 'selector' => "//div[@class='show-content-free']", 'required' => true, ), ), ); $spider = new phpspider($configs); $spider->start();
轻微解释一下一下句法的寄义:
//h1[@class='title']
猎取一切class值为title的h1节点
//div[@class='show-content-free']
猎取一切class值为show-content-free的div节点
打完代码后,记得依据要抓取的内容竖立对应的数据库、数据表,字段要能对对上。
接着cmd,输入:
php -f d:\jianshu\spider.php
运转以下:
翻开数据看一下,是不是是都抓取到了呢?
以上就是php爬虫框架怎样装置的细致内容,更多请关注ki4网别的相干文章!