php爬虫脚本
框架只做分发,不做数据处理,需要自己在回调中定制。
不限制采集方式,可以用正则,Xpath,字符串截取。
无限层级采集,可以实现列表->详情,列表->列表->详情,详情->详情等任意姿势采集。
队列去重,可以增量抓取,也可以全量采集。
支持调试模式,实时报表,守护模式。
安装依赖
环境
说明
php
>5.6,最好是php7以上
redis
数据队列
快速开始
1、复制代码到index.php文件中
if (!is_file('./vendor/autoload.php')) {
exec("composer require yangze/spiderx");
}
include_once __DIR__ . '/vendor/autoload.php';
$config = [
'name' => 'sina',
'tasknum' => 1,
'start' => [
'http://roll.news.sina.com.cn/news/gnxw/gdxw1/index.shtml',
],
'rule' => [
[
'name' => 'list',
'type' => 'list',
'url' => '#gdxw1/index_\d+.shtml#',
'data' => [
'title' => function ($pageInfo, $html, $data) {
preg_match_all('/
(.*?)/i', $html, $matches);$spider = new SpiderX\SpiderX($config);
$spider->on_fetch_list = function ($pageInfo, $html, $data) {
2、命令行执行(需要composer下载依赖,时间跟网速有关)
任务名称,队列名称根据name值生成。如果要做分布式的,可以选择用相同的name值
任务名称,队列名称根据name值生成。如果要做分布式的,可以选择用相同的name值
要采集的数据,以回调方式赋值,形式为:key => function ($pageInfo, $html, $data) { return '';}
on_start = function() use($spiderx) {
// 任务执行完成,可以发送通知,导入数据库,删除日志文件等
on_add_url = function($pageInfo) {
// 如果调转当前回调,需要返回true,才会向队列中添加数据
on_retry_page = function($pageInfo) {
setGetHtml = function($pageInfo) {
return file_get_contents($pageInfo['url']);
类似的还有setGetLinks方法,抽取页面中的链接,或者其他url存储方式
setGetLinks = function($html) {
需要依赖用户设置的每个rule下面单元的name值。假设我们设置的name值为news. 则对应的回调方法有:
on_loadding_{news,需要替换不同的name值} = function($pageInfo) {
on_loaded_{news,需要替换不同的name值} = function($pageInfo, $html) {
on_fetch_{news,需要替换不同的name值} = function($pageInfo, $html, $data) {
部分页面可能需要先get方式获取页面中的参数,然后再发起POST请求
$spider->on_start = function () use ($spider) {
'method' => 'post', // 发送post提交
'url' => 'http://127.0.0.1:3200/index.php/action/login?_=b0fd8734e0687a6cfe352e3f0fcbc5f6',
'referer' => 'http://127.0.0.1:3200/admin/',
'cookie' => true, // 需要共享cookie
'User-Agent' => 'testing/1.0',
'Accept' => 'application/json',
实现的方式就是在data的单元中,把url的值设置为上一个单元的name.DataField的形式
实现方式为自定义添加url队列,请求类型method为post,请求参数query为数组或者字符串形式:
'type' => 'detail', // 保持和单元的name,type一致
'url' => 'http://smeimdf.mofcom.gov.cn/news/searchEntpAudit.jsp',
'context' => [ // 上下文数据,可以很方便的在多任务中传数据
array_walk($data, function (&$item) {
$item = str_ireplace(',', ',', $item);
file_put_contents('data.csv', implode(',', $data) . "\n", FILE_APPEND | LOCK_EX);
demo/sina.php {command} [--opt -v -h ...] [arg0 arg1 arg2=value2 ...]
--debug Setting the application runtime debug level
--profile Display timing and memory usage information
--no-color Disable color/ANSI formessage output
-h, --help Display this helpmessage
-V, --version Show application version information
helpShow application helpinformation
list List all group and alone commands
version Show application version information
daemon Run script indaemon modal
debug Run script indebug modal
status Show the SpiderX status
stop Stop all the spiderX Process
More commandinformation, please use: demo/sina.php {command} -h