PHP simple_html_dom.php+正則 採集文章代碼_php技巧

來源:互聯網
上載者:User
複製代碼 代碼如下:

<?php
//包含PHP Simple html Dom 類庫檔案
include_once('./simplehtmldom/simple_html_dom.php');

//採集html
function getwebcontent($url){
$ch = curl_init();
$timeout = 10;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1);
$contents = trim(curl_exec($ch));
curl_close($ch);
return $contents;
}


//獲得標題和url
$string =
getwebcontent('http://www.babytree.com/learn/zhunbeihuaiyun/jijibeiyun/2');
//正則匹配<li>擷取標題和地址
preg_match_all ("/<li><a href=\"\/learn\/article\/(.*)\">(.*)<\/a>/",
$string, $out, PREG_SET_ORDER);

foreach($out as $key => $value){
$article['title'][] = $out[$key][2];
$article['link'][] = "http://www.babytree.com/learn/article/".$out[$key][1];
}

//根據url擷取文章內容
foreach($article['link'] as $key=>$value){
$html = file_get_html($value);
$div = $html->find('div[id=pagenum_0]');
$article[content][] = $div[0]->innertext;
}
//標題轉碼---真正用的時候不用這步--因為咱本來就要用utf8的
//不轉碼還真不能儲存成檔案
foreach($article[title] as $key=>$value){
$article[title][$key] = iconv('utf-8', 'gbk', $value);//轉碼
}
//存入檔案
$num = count($article['title']);
for($i=0; $i<$num; $i++){
file_put_contents("{$article[title][$i]}.txt", $article['content'][$i]);
}

/*本來想12點之前發的。。但小看一下都3點半了。。。 就算昨天的吧
本來擷取文章內容時用正則是最好的,速度也是最快的,
奈何正則是好,但Regex是真難!於是乎小查了一下,
網上也有很多人也在用PHP Simple Dom 雖然效率慢了點,但效果還是不錯的
從包含類庫檔案到寫入txt檔案 大概是7/8就秒 還有帶於進一步最佳化,特別是那擷取文章內容時的正則,那個太噁心了
大家可以小研究一下*/
?>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.