P.S. 2019年11月15日更新。

昨天一个朋友问我能否帮忙下载廖雪峰老师的python3教程,于是便写了这个php脚本。
在这里非常感谢廖雪峰老师的辛苦努力。

<?php
/**
* 获取Python3教程
* 感谢廖雪峰老师
* 教程地址: https://www.liaoxuefeng.com/wiki/1016959663602400
* 命令行下运行
* @AUTHOR: 杨永全
* @E-mail: qt06.com@139.com
* @URL: http://www.qt.hk/
* WEIBO: http://weibo.com/qt06
*/


$base_url = "https://www.liaoxuefeng.com/wiki/1016959663602400/";

 //获取教程目录页面
$s = file_get_contents("https://www.liaoxuefeng.com/wiki/1016959663602400");

//匹配出包含教程目录的html片段
preg_match('#<ul id="x-wiki-index" class="uk-nav uk-nav-side" style="margin-right:-15px;">(.*?)</ul>#is', $s, $rs);
$s1 = $rs[1];

//匹配出目录列表
preg_match_all('#<a href="/wiki/1016959663602400/(\d+)" class="x-wiki-index-item">(.+?)</a>#is', $s1,$list);

$cnt = count($list[1]);
for($i=0;$i< $cnt;$i++) {

    //命令行打印章节标题和地址
    echo ($i + 1) .$list[2][$i] . ',' . $list[1][$i]. "\r\n";

    //需要保存的文件名
    $filename = iconv('utf-8', 'gbk', ($i + 1) . ' ' . $list[2][$i] . '.txt');
    $filename = str_replace('/', '和', $filename);

    //获取教程详细内容
    $content_url = $base_url . $list[1][$i];
    $title = $list[2][$i];
    $s = file_get_contents($content_url);

    //匹配出详细内容
    preg_match('#<div class="x-wiki-content x-main-content">(.*?)</div>.*?<hr>#is',$s,$rs);
    $s = $rs[1];

    //过滤html标记,并适当处理空行
    $s = str_replace(">\n<",">\n\n<",$s);
    $s = strip_tags($s);
    $s = str_replace("\n\n\n", "\n\n", $s);
    $s = str_replace("\n\n\n", "\n\n", $s);
    $s = str_replace("\n\n\n", "\n\n", $s);

    //可能会有副作用,导致代码中的\\n被处理
    $s = str_replace("\n", "\r\n", $s);

    //处理html实体字符
    $s = html_entity_decode($s);

    //$s = str_replace('&gt;', '>', $s);
    //$s = str_replace('&#39;','\"', $s);

    //保存到当前目录,windows的文件名必须是gbk
    file_put_contents($filename, "$title\r\n\r\n$s\r\n\r\n原文地址: $content_url");
}

//弹出对话框提示完成
passthru("mshta javascript:alert('finished.".$cnt."');window.close();");

标签: none

评论已关闭