PHP蜘蛛爬虫开发文档

PHP蜘蛛爬虫开发文档

官方文档

  1. https://doc.phpspider.org/

githup地址

  1. https://github.com/owner888/phpspider

phpspider-master/core 文件介绍

文件名 描述
init.php 公共入口文件
constans.php 公共入口文件
phpspider.php 核心类文件
- -
configs详解 -
requests.php 请求类文件
selector.php 选择器类文件
db.php 数据库类文件
cache.php 缓存类文件
log.php 日志类文件
queue.php Redis操作类文件
util.php 实用函数集合类文件
worker.php 多进程操作类

加载核心文件

  1. require './vendor/autoload.php';
  2. use phpspider\core\phpspider;

requests.php 请求类 详解

成员 描述
input_encoding 输入编码明确指定输入的页面编码格式(UTF-8,GB2312,…..),防止出现乱码,如果设置null则自动识别
output_encoding 输出编码明确指定输出的编码格式(UTF-8,GB2312,…..),防止出现乱码,如果设置null则为utf-8
encoding 获取网页编码
content 获取响应内容 - 转码前内容
text 获取响应内容 - 转码后内容
status_code 网页状态码
headers 获取响应头
request 获取请求头
  1. # 加载 核心文件

  2. require './vendor/autoload.php';

  3. use phpspider\core\phpspider;

  4. # 加载 请求类文件

  5. use phpspider\core\requests;

  6. # 设置 输入编码

  7. requests::$input_encoding = null; // null=自动识别

  8. # 设置 输出编码

  9. requests::$output_encoding = null; // null=utf-8

  10. # 获取 网页编码

  11. request::$encoding;

  12. # 获取 响应内容 - 转码前内容

  13. request::$content;

  14. # 获取 响应内容 - 转码后内容

  15. request::$text;

  16. # 获取 网页状态码

  17. request::$status_code;

  18. # 获取 获取响应头

  19. request::$headers;

  20. # 获取 获取请求头

  21. request::$request;

方法 描述
set_timeout( $timeout ) 设置请求超时时间
set_proxy( $proxy ) 设置请求代理
set_useragent( $useragent ) 浏览器useragent(UA)
set_referer( $referer ) 浏览器请求来路URL
set_header( $key, $value ) 添加请求的Header
set_cookie( $key, $value, $domain = ‘’ ) 添加请求的Cookie
get_cookie( $name, $domain = ‘’ ) 获取请求的Cookie
set_cookies( $cookies, $domain = ‘’ ) 设置请求Cookie
get_cookie( $domain = ‘’ ) 获取请求的Cookie
set_client_ip( $ip ) 设置请求伪IP
set_hosts( $host, $ips ) 设置请求的第三方主机和IP
get( $url, $params, $allow_redirects, $cert ) 用来获取某个网页
post( $url, $params, $files, $allow_redirects, $cert ) 用来获取某个网页
put( $url, $params, $allow_redirects, $cert ) 用来获取某个网页
delete( $url, $params, $allow_redirects, $cert ) 用来获取某个网页
  1. # 设置 请求超时时间

  2. # 1. 单一值 (同时设置connect和read)

  3. requests::set_timeout(10);

  4. # 2. 数组值 (设置connect和read二者的timeout)

  5. requests::set_timeout( array(3, 27) );

  6. # 设置 请求代理

  7. 1. 字符串

  8. requests::set_proxy('http://user:pass@host:port');

  9. 2. 数组

  10. requests::set_proxy(

  11. array(

  12. 'http://user:pass@host:port',

  13. 'http://user:pass@host:port'

  14. )

  15. );

  16. # 设置 UA头

  17. // 1. 字符串

  18. requests::set_useragent("Mozilla/4.0 (compatible; MSIE 6.0; ) Opera/UCWEB7.0.2.37/28/");

  19. // 2. 数组

  20. requests::set_proxy(

  21. array(

  22. "Mozilla/4.0 (compatible; MSIE 6.0; ) Opera/UCWEB7.0.2.37/28/",

  23. "Mozilla/4.0 (compatible; MSIE 6.0; ) Opera/UCWEB7.0.2.37/28/"

  24. )

  25. );

  26. # 设置 请求来路URL

  27. requests::set_referer('https://www.baidu.com');

  28. # 设置 请求的Header

  29. requests::set_header("Referer", "http://www.baidu.com");

  30. # 添加 请求的Cookie

  31. requests::set_cookie("BAIDUID", "FEE96299191CB0F11954F3A0060FB470:FG=1", "http://www.baidu.com");

  32. requests::set_cookie("BAIDUID=FEE96299191CB0F11954F3A0060FB470:FG=1", "http://www.baidu.com");

  33. # 获取 请求的Cookie

  34. requests::get_cookie("BAIDUID", "http://www.baidu.com");

  35. requests::get_cookie("http://www.baidu.com");

  36. # 设置 设置请求伪IP

  37. // 1. 单一值

  38. requests::set_client_ip("192.168.0.2");

  39. // 2. 数组

  40. requests::set_client_ip(

  41. array(

  42. "192.168.0.1",

  43. "192.168.0.2"

  44. )

  45. );

  46. # 设置 请求的第三方主机和IP

  47. requests::set_hosts(

  48. "http://www.baidu.com",

  49. array(

  50. "203.195.143.21",

  51. "203.195.143.22"

  52. )

  53. );

  54. # 发起 get 请求

  55. requests::get("https://github.com/timeline.json");

  56. # 发起 post 请求

  57. // 1. 登录

  58. requests::post(

  59. "http://www.domain.com",

  60. array(

  61. "username" => "test", "password" => "test"

  62. )

  63. );

  64. // 2. 文件上传

  65. request::post(

  66. "http://www.domain.com",

  67. null,

  68. array(

  69. "file1" => "test1.jpg",

  70. "file2" => "test2.jpg"

  71. )

  72. );

  73. # 发起 put 请求

  74. requests::put(

  75. "http://www.domain.com",

  76. "{username:\"test888\",username:\"123456\"}"

  77. );

  78. # 发起 delete 请求

  79. requests::delete(

  80. "http://www.domain.com",

  81. "{username:\"test888\"}"

  82. );


selector.php 选择器类 详解

方法 描述
select( $html, $selector, $selector_type = ‘xpath’ ) 选择匹配的内容
remove( $html, $selector, $selector_type = ‘xpath’ ) 删除匹配的内容
  1. /**

  2. * select( $html, $selector, $selector_type = 'xpath' )

  3. * @param $html 需要筛选的网页内容

  4. * @param $selector 选择器规则

  5. * @param $selector_type 选择器类型: xpath (默认) / regex / css

  6. */

  7. # 1. xpath

  8. $html = requests::get("https://news.163.com/20/0831/15/FLCBLJOT000189FH.html");

  9. $data = selector::select($html, '//*[@id="endText"]'); // 读取 网易新闻 新闻内容

  10. var_dump($data);

  11. # 2. css

  12. $html = requests::get("https://news.163.com/20/0831/15/FLCBLJOT000189FH.html");

  13. $data = selector::select($html, ".post_content_main > h1", "css"); // 读取 网易新闻 详情页标题

  14. var_dump($data);

  15. # 3. regex

  16. $html = requests::get("https://news.163.com/20/0831/15/FLCBLJOT000189FH.html");

  17. $data = selector::select($html, "@<title>(.*?)</title>@", "regex"); // 读取 网易新闻 title标题内容

  18. var_dump($data);

  19. /**

  20. * remove( $html, $selector, $selector_type = 'xpath' )

  21. * @param $html 需要筛选的网页内容

  22. * @param $selector 选择器规则

  23. * @param $selector_type 选择器类型: xpath (默认) / regex / css

  24. */

  25. $html = requests::get("https://news.163.com/20/0831/15/FLCBLJOT000189FH.html");

  26. $html = selector::select($html, '//*[@id="endText"]'); // 读取 网易新闻 新闻内容

  27. // 在上面获取的内容基础上,删除第一个<p>标签(原标题)

  28. $data = selector::select($html, '//*[@id="endText"]/p[1]');

  29. var_dump($data);


db.php 数据库类 详解

  1. # 数据配置链接
  2. $db_config = array(
  3. 'host' => '127.0.0.1',
  4. 'port' => 3306,
  5. 'user' => 'root',
  6. 'pass' => '123456',
  7. 'name' => 'demo_db'
  8. );
  9. // 数据库配置
  10. db::set_connect('default', $db_config);
  11. // 数据库连接
  12. db::init_mysql();
方法 描述
query($sql) 原生SQL操作
get_one($sql) 原生SQL操作
get_all($sql) 单条查询
insert($table, $data) 单条插入
insert_batch($table, $data) 单条修改
update_batch($table, $data, $index) 批量修改
delete($table, $where) 单条删除
  1. # query 原生操作

  2. // 1. 查询

  3. $query = db::query("select * fromcontent");

  4. while($row = db::fetch($query)) {

  5. echo "id = {$row['id']}; name = {$row['name']}; \n";

  6. }

  7. // 2. 新增

  8. db::query("insert intocontent(name) values (test);");

  9. // 3. 更新

  10. db::query("updatecontentsetname='test' whereid=1;");

  11. // 4. 删除

  12. db::query("delete fromcontentwhereid=1;");

  13. # get_one

  14. $row = db::get_one("select * fromcontentwhereid=1;");

  15. # get_all

  16. $rows = db::get_all("select * fromcontentlimit 5;");

  17. # insert

  18. $rows = db::insert('content', array('name' => 'test'));

  19. # insert_batch

  20. $rows = db::insert_batch(

  21. 'content',

  22. array(

  23. array(

  24. 'name' => 'test1'

  25. ),

  26. array(

  27. 'name' => 'test2'

  28. )

  29. )

  30. );

  31. # update_batch

  32. db::update_batch(

  33. 'content',

  34. array(

  35. array(

  36. 'id' => 1,

  37. 'name' => 'test1'

  38. ),

  39. array(

  40. 'id' => 2,

  41. 'name' => 'test2'

  42. )

  43. ),

  44. 'id' // 以 id 为条件进行修改

  45. );

  46. # delete

  47. $rows = db::delete('content', "id=1");


使用 configs 来编写爬虫

  1. # 加载 核心文件

  2. require './vendor/autoload.php';

  3. use phpspider\core\phpspider;

  4. # 官方文档说不要删除这段注释,我并不知道有什么用,文档说加就加

  5. /* Do NOT delete this comment */

  6. /* 不要删除这段注释 */

  7. # $configs = array(

  8. 'name' => '163新闻', // 当前爬虫名称

  9. 'log_show' => false, // 是否显示日志, 默认false, 可选 true (显示调试信息) | false (显示爬取面板, tail -f data/phpspider.log 查看日志)

  10. 'log_file' => 'data/phpspider.log', // 日志文件路径, 默认 data/phpspider.log

  11. 'log_type' => '', // 显示和记录的日志类型, 默认空, 可选 info(普通) | warn(警告) | debug(调试) | error(错误 )

  12. 'input_encoding' => null, // 输入编码, 默认null(自动识别)

  13. 'output_encoding' => null, // 输出编码, 默认null(null=utf-8)

  14. 'tasknum' => 1, // 同时工作的爬虫任务数, 默认1(单进程任务爬取)

  15. 'multiserver' => false, // 多服务器处理, 默认false, 可选 true | false

  16. 'serverid' => 1, // 服务器ID, 默认1, 启用第二天服务器可设置为2

  17. 'save_running_state' => false, // 保存爬虫运行状态, 默认false(不保存), 可选 true | false

  18. 'queue_config' => array( // redis 配置, 保存爬虫运行状态、多任务处理 和 多服务器处理 都需要 redis 来保存采集任务数据

  19. 'host' => '127.0.0.1',

  20. 'port' => 6379,

  21. 'pass' => '',

  22. 'db' => 5,

  23. 'prefix' => 'phpspider',

  24. 'timeout' => 30

  25. ),

  26. 'proxy' => array( // 代理服务器,如果爬取的网站根据ip做了反爬虫,可以设置此项

  27. 'http://host:port',

  28. 'http://user:pass@host:port',

  29. ),

  30. 'interval' => 1000, // 爬取单个网页的时间间隔, 单位毫秒

  31. 'timeout' => 5, // 爬取每个网页的超时时间, 单位秒

  32. 'max_try' => 0, // 爬取每个网页失败后尝试次数, 默认0(不重复爬取)

  33. 'max_depth' => 0, // 爬取网页深度, 超过深度的页面不再采集, 默认0(不限制)

  34. 'max_fields' => 0, // 爬取内容网页最大条数, 默认0(不限制)

  35. 'user_agent' => "", // 爬取网页所使用的浏览器类型

  36. // 1. 枚举类型

  37. // phpspider::AGENT_ANDROID, 表示爬虫爬取网页时, 使用安卓手机浏览器

  38. // phpspider::AGENT_IOS, 表示爬虫爬取网页时, 使用苹果手机浏览器

  39. // phpspider::AGENT_PC, 表示爬虫爬取网页时, 使用PC浏览器

  40. // phpspider::AGENT_MOBILE, 表示爬虫爬取网页时, 使用移动设备浏览器

  41. // 2. 自定义类型

  42. // 'user_agent' => "Mozilla/5.0"

  43. // 3. 随机浏览器类型

  44. // 'user_agent' => array(

  45. // "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36",

  46. // "Mozilla/5.0 (iPhone; CPU iPhone OS 9_3_3 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13G34 Safari/601.1",

  47. // "Mozilla/5.0 (Linux; U; Android 6.0.1;zh_cn; Le X820 Build/FEXCNFN5801507014S) AppleWebKit/537.36 (KHTML, like Gecko)Version/4.0 Chrome/49.0.0.0 Mobile Safari/537.36 EUI Browser/5.8.015S",

  48. // );

  49. 'client_ip' => "", // 爬取网页所使用的伪IP,用于破解防采集

  50. // 1. 字符串类型

  51. // 'client_ip' => '192.168.0.2'

  52. // 2. 数组类型

  53. // 'client_ip' => array(

  54. // '192.160.0.1',

  55. // '192.160.0.2',

  56. // );

  57. 'export' => array( // 爬取数据数据导出

  58. 'type' => 'csv', // 导出类型 csv | sql | db

  59. 'file' => './data/163_news.csv', // 导出文件路径

  60. // 'type' => 'sql'

  61. // 'file' => './data/163_news.sql',

  62. // 'table' => 'news_table', // 导出db、sql数据库表名

  63. // 'type' => 'db'

  64. // 'table' => 'news_table', // 导出db、sql数据库表名

  65. ),

  66. 'db_config' => array( // 数据库配置

  67. 'host' => '127.0.0.1',

  68. 'port' => 3306,

  69. 'user' => 'root',

  70. 'pass' => 'root',

  71. 'name' => 'demo',

  72. ),

  73. 'domains' => array( // 定义爬虫爬取哪些域名下的网页, 非域名下的url会被忽略以提高爬取速度

  74. '163.com',

  75. 'new.163.com'

  76. ),

  77. 'scan_urls' => array( // 定义爬虫的入口链接, 爬虫从这些链接开始爬取,同时这些链接也是监控爬虫所要监控的链接

  78. 'https://news.163.com'

  79. ),

  80. 'content_url_regexes' => array( // 定义内容页url的规则, 正则表达式 最好填写以提高爬取效率

  81. 'https://news.163.com/\d+/\d+/\d+/\w+.html'

  82. ),

  83. 'list_url_regexes' => array( // 定义列表页url的规则, 对于有列表页的网站, 使用此配置可以大幅提高爬虫的爬取速率

  84. 'https://news.163.com/gz/page/\d+.html'

  85. ),

  86. 'fields' => array( // 定义内容页的抽取规则, 规则由一个个field组成, 一个field代表一个数据抽取项

  87. array(

  88. 'name' => "content", // 名称, 不能为空

  89. 'selector' => '//*[@id="endText"]', // 定义抽取规则, 不能为空, 默认使用xpath

  90. 'selector_type' => 'xpath', // 抽取规则类型, 默认xpath, 可选 xpaht | jsonpath | regex

  91. 'required' => true, // 是否必须的, 默认false, 可选 true | false

  92. 'repeated' => false, // 抽取到的内容是否多项, 默认false, 可选 false | true(结果都是数组类型)

  93. 'children' => array( // 为此field定义子项, 子项的定义仍然是一个fields数组

  94. array(

  95. 'name' => 'replay', // # 例如抽取新闻下面的评论

  96. 'selector' => "//div[contains(@class,'replay')]"

  97. )

  98. ),

  99. 'source_type' => 'url_content', // 该field的数据源, 默认从当前的网页 (url_context) 中抽取数据, 可选 url_context | attached_url

  100. // 'source_type' => 'attached_url',

  101. // 'attached_url' => 'https://news.163.com/{comment_id}/comments', // 当source_type设置为attached_url时, 定义新请求的url

  102. ),

  103. array(

  104. 'name' => "title",

  105. 'selector' => '//*[@id="epContentLeft"]/h1',

  106. )

  107. )

  108. );

  109. // 载入配置

  110. $spider = new phpspider($configs);

  111. // 启动爬虫

  112. $spider->start();

本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!