本文使用了php-cli
的方式运行,请先确保已经安装php-cli并加入环境变量: 终端输入 php -v
看看是否能返回版本信息。
本教程旨在练习命令行与composer的使用,可以参考php的包管理工具Composer的安装与使用了解更多
本项目需要PHP7以上版本
初始化项目
新建空目录(下文称:项目目录),打开终端切换到项目目录
项目名称形如 <author>/<projectname>
,其余一路回车
项目目录中新建index.php
,内容如下:
1 2
| <?php require __DIR__.'/vendor/autoload.php';
|
安装http请求库
本项目使用的是guzzlehttp/guzzle
,完整的手册看这里:Quickstart - Guzzle Documentation
1
| composer require guzzlehttp/guzzle
|
此时 观察项目目录结构如下
1 2 3 4
| ├─vendor ├─composer.json ├─composer.lock └─index.php
|
其中composer.json
中添加了require
信息,生成的composer.lock
记录了当前所有安装的php组件的版本,vendor
是当前项目的所有第三方依赖的安装位置
在index.php
中追加一行
添加CA文件
下载cacert.pem,也可以从网盘下载(网盘文件需解压)
下载完成后保存,打开PHP安装目录,找到php.ini
文件,打开、搜索;openssl.cafile=
,修改为:
1
| openssl.cafile=下载的路径到/cacert.pem
|
添加完后GuzzleHttp\Client
就可以使用了,可以测试一下:
1 2 3 4 5 6 7 8
| <?php require __DIR__.'/vendor/autoload.php'; use GuzzleHttp\Client;
$client = new Client(['base_uri' => 'https://www.lmlq.com/', 'timeout' => 5.0]); $response = $client->request('GET', 'News/GroupNews/');
var_dump((string) $response->getBody());
|
安装HTML解析库
本项目使用的是voku/simple_html_dom
,其选择器与jQuery
相同。完整的手册看这里:simple html dom parser
1 2
| composer require voku/simple_html_dom composer require voku/portable-utf8
|
在index.php
中追加一行
1
| use voku\helper\HtmlDomParser;
|
开始抓取、解析列表页
还以刚刚的页面为例子,增加页面解析部分,尝试获取栏目中的内页地址:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
$body = (string) $response->getBody(); $dom = HtmlDomParser::str_get_html($body);
$a_list = $dom->findMultiOrFalse('.img_list li a');
$href_list = []; if ($a_list !== false) { foreach ($a_list as $a) { array_push($href_list, $a->getAttribute('href')); } } print_r($href_list);
|
获取内页数据,获得新闻标题与正文
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
$res = [];
foreach($href_list as $href) { $response = $client->request('GET', '/News/GroupNews/10313.html'); $body = (string) $response->getBody(); $dom = HtmlDomParser::str_get_html($body); array_push($res, [ 'title' => $dom->findOneOrFalse('title')->textContent, 'content' => $dom->findOneOrFalse('.cont')->textContent ]); } print_r($res);
|
这里将会打印当前列表下的几篇文章的内容。
完整代码如下,每行都加了注释:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| <?php require __DIR__ . '/vendor/autoload.php';
use GuzzleHttp\Client; use voku\helper\HtmlDomParser;
$client = new Client(['base_uri' => 'https://www.lmlq.com/', 'timeout' => 5.0]); $response = $client->request('GET', 'News/GroupNews/');
$body = (string) $response->getBody(); $dom = HtmlDomParser::str_get_html($body);
$a_list = $dom->findMultiOrFalse('.img_list li a');
$href_list = []; if ($a_list !== false) { foreach ($a_list as $a) { array_push($href_list, $a->getAttribute('href')); } }
$res = [];
foreach($href_list as $href) { $response = $client->request('GET', $href); $body = (string) $response->getBody(); $dom = HtmlDomParser::str_get_html($body); array_push($res, [ 'title' => $dom->findOneOrFalse('title')->textContent, # 取得标题 'content' => $dom->findOneOrFalse('.cont')->textContent # 取得正文 ]); } print_r($res);
|