本文实例讲述了php实现的抓取小说网站内容功能。分享给大家供大家参考,具体如下:

爬取免费内容,弄到手机,听书,妥妥的。

ini_set('user_agent','mozilla/4.0 (compatible; msie 7.0; windows nt 5.1; .net clr 2.0.50727; .net clr 3.0.04506.30; greenbrowser)');
ini_set('max_execution_time', '0');
$base = 'https://www.qu.la/book/19434/';
$start = '7504808.html';
$content_grep = '/    (.*)<br\/>/';
//$content_grep = '/<div id="content">(.*)<br\/>/ss';
$next_grep = '/<a id="pager_next" href=\"(\d+\.html)\" target="_top" class="next">下一章<\/a>/';
$next = $start;
$file_name = '听书了.txt';
while($next) {
  echo 'getting ' . $next . php_eol;
  $result = file_get_contents($base . $next);
  preg_match_all($content_grep, $result, $match);
  $istitle = true;
  $content = "";
  foreach($match[1] as $line) {
    $line  = str_replace("<br/>", '', $line);
    $line  = str_replace(" ", '', $line);
    if($istitle) {
      $content = $line . php_eol . php_eol;
      $istitle = false;
    } else {
      $content .= '    ' . $line . php_eol . php_eol;
    }
  }
  $file = fopen($file_name, 'a');
  echo 'write length: ' . strlen($content) . php_eol;
  fwrite($file, $content);
  fclose($file);
  echo '.';
  preg_match($next_grep, $result, $match);
  $next = $match[1];
}