抓取网络小说 为txt

博主分享了如何从网络上抓取小说并将其转化为TXT文本的过程,旨在方便阅读。欢迎提出改进建议,共同提升技能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本人比较喜欢看小说但是网络上在线看的比较多,txt文本形式的比较少,简单写个抓取文本,写文件

如有意见建议  希望能提出来共同进步

<?php
define("URL_LANG","http://*****.net/novel/4/4469/");//目录url
define("URL_CENT","http://*****.net/novel/4/4469/");//内容url
define('MENU_REG','|<a href="(.*?).html">(.*?)</a>|i');//目录读取详细页面正则
define("TITLE_REG","|<dt>(.*)</dt>|i");//标题正则
define('CENTENT_REG','|<div id="booktext">(.*)</div>|i');//内容正则
define("FILE_NAME","神印王座.txt");//下载文件名称
set_time_limit(0);//延时不过去
// 从主机名中取得后面两段
if (ob_get_level() == 0) ob_start();
$arr=getmenu();

foreach($arr as $key=>$val){
	$content=getcontent($val);
	if($content){
		write($content);
		echo $key.'--'.gettitle($val).'--'.date('Y-m-d h:i:s')."<br>";  
	}else{
		echo gettitle($val).'<失败>';
	}
	
	
	echo str_pad('',4096)."\n";    
	ob_flush();
	flush();
	sleep(1);
	
	clearstatcache();
}
echo '下载完毕';
ob_end_flush();
exit;


//根据网址读取  标题 + 文章
function getcontent($page,$cou=1){
	//获取不成功  再来一遍
	$urllang=URL_CENT;
	try{
		$content = file_get_contents($urllang.$page.'.html');
		if($content){
			preg_match_all (TITLE_REG,$content,$title_tmp);
			preg_match_all (CENTENT_REG,$content,$content_tmp);
			$res=$title_tmp[1][0].'==='.$content_tmp[1][0];
			$res=strip_tags($res);
			$res=preg_replace('/( )/i','',$res);
			return $res;
		}
	}catch(Exception $e){
		if($cou<5){
			
			getcontent($page,++$cou);
			
		}else{
			
			return false;	
			
		}
		
	}
	
	
	
}
function gettitle($page){
	$urllang=URL_CENT;
	$content = file_get_contents($urllang.$page.'.html');
	if($content){
		preg_match_all (TITLE_REG,$content,$title_tmp);
		
		$res=$title_tmp[1][0];
		return $res;
	}
	
}

//追加写入文本文件
function write($str){
	$james=fopen(FILE_NAME,"a");
	fwrite($james,$str);
	fclose($james);
		
}
//读取目录返回数组
function getmenu(){
	$urllang=URL_LANG;
	$content = file_get_contents($urllang);
	
	//preg_match_all ('|<div class="book_article_texttable">(.*)</div>|i',$content,$title_tmp);
	
	preg_match_all(MENU_REG,$content,$title_arr);
	
	return  $title_arr[1];
}

?>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值