當前位置:博客首頁>>PHP >> 閱讀正文

php實現(xiàn)的網(wǎng)頁正文提取算法

作者: 鄭曉 分類: PHP 發(fā)布于: 2014-11-20 19:49 瀏覽:16,548 評論(16)


Html2Article-php實現(xiàn)的提取網(wǎng)頁正文部分,最近研究百度結(jié)果頁的資訊采集,其中關(guān)鍵環(huán)節(jié)就是從采集回的頁面中提取出文章。

有網(wǎng)友回復說不會用或不能用,鄭曉特意貼上測試代碼…做為一個程序員,有問題請先自己找原因

#采集我們新聞網(wǎng)的一個新聞頁
$content = file_get_contents("http://news.qingdaonews.com/qingdao/2016-12/26/content_11882489.htm");
$r = new Readability($content);
print_r($r->getContent());

因為難點在于如何去識別并保留網(wǎng)頁中的文章部分,而且刪除其它無用的信息,并且要做到通用化,不能像火車頭那樣根據(jù)目標站來制定采集規(guī)則,因為搜索引擎結(jié)果中有各種的網(wǎng)頁。

這個類是從網(wǎng)上找到的一個php實現(xiàn)的提取網(wǎng)頁正文部分的算法,鄭曉在本地也測試了下,準確率非常高。

source = $source;

// DOM 解析類只能處理 UTF-8 格式的字符
$source = mb_convert_encoding($source, 'HTML-ENTITIES', $input_char);

// 預處理 HTML 標簽,剔除冗余的標簽等
$source = $this->preparSource($source);

// 生成 DOM 解析類
$this->DOM = new DOMDocument('1.0', $input_char);
try {
//libxml_use_internal_errors(true);
// 會有些錯誤信息,不過不要緊 :^)
if (!@$this->DOM->loadHTML(''.$source)) {
throw new Exception("Parse HTML Error!");
}

foreach ($this->DOM->childNodes as $item) {
if ($item->nodeType == XML_PI_NODE) {
$this->DOM->removeChild($item); // remove hack
}
}

// insert proper
$this->DOM->encoding = Readability::DOM_DEFAULT_CHARSET;
} catch (Exception $e) {
// ...
}
}

/**
* 預處理 HTML 標簽,使其能夠準確被 DOM 解析類處理
*
* @return String
*/
private function preparSource($string) {
// 剔除多余的 HTML 編碼標記,避免解析出錯
preg_match("/charset=([\w|\-]+);?/", $string, $match);
if (isset($match[1])) {
$string = preg_replace("/charset=([\w|\-]+);?/", "", $string, 1);
}

// Replace all doubled-up
tags with

tags, and remove fonts.
$string = preg_replace("/[ \r\n\s]*/i", "

", $string);
$string = preg_replace("/<\/?font[^>]*>/i", "", $string);

// @see https://github.com/feelinglucky/php-readability/issues/7
// - from http://stackoverflow.com/questions/7130867/remove-script-tag-from-html-content
$string = preg_replace("#(.*?)#is", "", $string);

return trim($string);
}

/**
* 刪除 DOM 元素中所有的 $TagName 標簽
*
* @return DOMDocument
*/
private function removeJunkTag($RootNode, $TagName) {

$Tags = $RootNode->getElementsByTagName($TagName);

//Note: always index 0, because removing a tag removes it from the results as well.
while($Tag = $Tags->item(0)){
$parentNode = $Tag->parentNode;
$parentNode->removeChild($Tag);
}

return $RootNode;

}

/**
* 刪除元素中所有不需要的屬性
*/
private function removeJunkAttr($RootNode, $Attr) {
$Tags = $RootNode->getElementsByTagName("*");

$i = 0;
while($Tag = $Tags->item($i++)) {
$Tag->removeAttribute($Attr);
}

return $RootNode;
}

/**
* 根據(jù)評分獲取頁面主要內(nèi)容的盒模型
* 判定算法來自:http://code.google.com/p/arc90labs-readability/
* 這里由鄭曉博客轉(zhuǎn)發(fā)
* @return DOMNode
*/
private function getTopBox() {
// 獲得頁面所有的章節(jié)
$allParagraphs = $this->DOM->getElementsByTagName("p");

// Study all the paragraphs and find the chunk that has the best score.
// A score is determined by things like: Number of

's, commas, special classes, etc.
$i = 0;
while($paragraph = $allParagraphs->item($i++)) {
$parentNode = $paragraph->parentNode;
$contentScore = intval($parentNode->getAttribute(Readability::ATTR_CONTENT_SCORE));
$className = $parentNode->getAttribute("class");
$id = $parentNode->getAttribute("id");

// Look for a special classname
if (preg_match("/(comment|meta|footer|footnote)/i", $className)) {
$contentScore -= 50;
} else if(preg_match(
"/((^|\\s)(post|hentry|entry[-]?(content|text|body)?|article[-]?(content|text|body)?)(\\s|$))/i",
$className)) {
$contentScore += 25;
}

// Look for a special ID
if (preg_match("/(comment|meta|footer|footnote)/i", $id)) {
$contentScore -= 50;
} else if (preg_match(
"/^(post|hentry|entry[-]?(content|text|body)?|article[-]?(content|text|body)?)$/i",
$id)) {
$contentScore += 25;
}

// Add a point for the paragraph found
// Add points for any commas within this paragraph
if (strlen($paragraph->nodeValue) > 10) {
$contentScore += strlen($paragraph->nodeValue);
}

// 保存父元素的判定得分
$parentNode->setAttribute(Readability::ATTR_CONTENT_SCORE, $contentScore);

// 保存章節(jié)的父元素,以便下次快速獲取
array_push($this->parentNodes, $parentNode);
}

$topBox = null;

// Assignment from index for performance.
// See http://www.peachpit.com/articles/article.aspx?p=31567&seqNum=5
for ($i = 0, $len = sizeof($this->parentNodes); $i < $len; $i++) { $parentNode = $this->parentNodes[$i];
$contentScore = intval($parentNode->getAttribute(Readability::ATTR_CONTENT_SCORE));
$orgContentScore = intval($topBox ? $topBox->getAttribute(Readability::ATTR_CONTENT_SCORE) : 0);

if ($contentScore && $contentScore > $orgContentScore) {
$topBox = $parentNode;
}
}

// 此時,$topBox 應(yīng)為已經(jīng)判定后的頁面內(nèi)容主元素
return $topBox;
}

/**
* 獲取 HTML 頁面標題
*
* @return String
*/
public function getTitle() {
$split_point = ' - ';
$titleNodes = $this->DOM->getElementsByTagName("title");

if ($titleNodes->length
&& $titleNode = $titleNodes->item(0)) {
// @see http://stackoverflow.com/questions/717328/how-to-explode-string-right-to-left
$title = trim($titleNode->nodeValue);
$result = array_map('strrev', explode($split_point, strrev($title)));
return sizeof($result) > 1 ? array_pop($result) : $title;
}

return null;
}

/**
* Get Leading Image Url
*
* @return String
*/
public function getLeadImageUrl($node) {
$images = $node->getElementsByTagName("img");

if ($images->length && $leadImage = $images->item(0)) {
return $leadImage->getAttribute("src");
}

return null;
}

/**
* 獲取頁面的主要內(nèi)容(Readability 以后的內(nèi)容)
*
* @return Array
*/
public function getContent() {
if (!$this->DOM) return false;

// 獲取頁面標題
$ContentTitle = $this->getTitle();

// 獲取頁面主內(nèi)容
$ContentBox = $this->getTopBox();

//Check if we found a suitable top-box.
if($ContentBox === null)
throw new RuntimeException(Readability::MESSAGE_CAN_NOT_GET);

// 復制內(nèi)容到新的 DOMDocument
$Target = new DOMDocument;
$Target->appendChild($Target->importNode($ContentBox, true));

// 刪除不需要的標簽
foreach ($this->junkTags as $tag) {
$Target = $this->removeJunkTag($Target, $tag);
}

// 刪除不需要的屬性
foreach ($this->junkAttrs as $attr) {
$Target = $this->removeJunkAttr($Target, $attr);
}

$content = mb_convert_encoding($Target->saveHTML(), Readability::DOM_DEFAULT_CHARSET, "HTML-ENTITIES");

// 多個數(shù)據(jù),以數(shù)組的形式返回
return Array(
'lead_image_url' => $this->getLeadImageUrl($Target),
'word_count' => mb_strlen(strip_tags($content), Readability::DOM_DEFAULT_CHARSET),
'title' => $ContentTitle ? $ContentTitle : null,
'content' => $content
);
}

function __destruct() { }
}

使用起來也非常簡單,實例化時傳入網(wǎng)頁的html源碼和相應(yīng)的編碼,然后直接調(diào)用其getContent方法即可返回提取到的正文部分,提取出的文章中可能還會含有少部分鏈接,可以自己后期再修改。

? ? ? ?

本文采用知識共享署名-非商業(yè)性使用 3.0 中國大陸許可協(xié)議進行許可,轉(zhuǎn)載時請注明出處及相應(yīng)鏈接。

本文永久鏈接: http://www.yjfs.org.cn/html2article-php.html

php實現(xiàn)的網(wǎng)頁正文提取算法:目前有16 條留言

用戶評論頭像 博主你好發(fā)表于 2020年11月06日 10:25[回復]

博主,這個太好了,可以加你了解一下嗎,正需要抽取正文的算法

    用戶評論頭像 鄭曉發(fā)表于 2020年11月06日 10:31[回復]

    這個類我也是從其它地方找的,并不是我寫的,我也沒研究過這種算法。

用戶評論頭像 braincy發(fā)表于 2017年09月26日 17:49[回復]

blog.sciencenet.cn/blog-76913-903050.html
這篇網(wǎng)站抓下來的內(nèi)容為什么是亂碼呀??

用戶評論頭像 心痛發(fā)表于 2017年09月11日 11:21[回復]

為什么我解析網(wǎng)頁調(diào)用方法 不是超時就是 內(nèi)存不足 有什么解決辦法嗎 是什么原因引起的呢 希望幫幫忙 謝謝博主!

用戶評論頭像 fansartg發(fā)表于 2017年02月23日 02:19[回復]

測試抓取新浪博客文章不行,抓取163博客內(nèi)容失敗,抓取普通網(wǎng)站頁面成功,還是有待改進。

用戶評論頭像 貪得無厭的海牛發(fā)表于 2016年12月05日 20:58[回復]

非常抱歉,我實在是個小白,請問[實例化時傳入網(wǎng)頁的html源碼和相應(yīng)的編碼,然后直接調(diào)用其getContent方法即可返回提取到的正文部分]可以麻煩您解釋下具體怎么操作嗎?

    用戶評論頭像 鄭曉發(fā)表于 2016年12月06日 09:29[回復]

    比如你用file_get_contents()打開一個網(wǎng)頁,它的返回值就是網(wǎng)頁的html源碼,我們把它保存到$content變量中, 然后就可以實例化這個正文提取類,如$obj=new Readability($content); 因為編碼是默認的可以不傳(這里假設(shè)我的目標站是utf8編碼), 最后調(diào)用$obj->getContent(); 可以獲取到正文內(nèi)容。可以把它的返回值保存到你需要的變量中。

      用戶評論頭像 貪得無厭的海牛發(fā)表于 2016年12月10日 18:57[回復]

      太感謝了!我再試試!謝謝您的回復

      用戶評論頭像 孤寒的海星發(fā)表于 2016年12月26日 16:04[回復]

      我這樣寫了,沒有內(nèi)容顯示

        用戶評論頭像 鄭曉發(fā)表于 2016年12月26日 16:12[回復]

        收到你的評論后我直接測試了一遍,是沒問題的,文章上面已經(jīng)貼出測試代碼。

          用戶評論頭像 恭順的鍋貼發(fā)表于 2016年12月26日 16:17[回復]

          我換了很多網(wǎng)站··可是結(jié)果只有出現(xiàn)一個Array,請問您知道原因么?謝謝

            用戶評論頭像 鄭曉發(fā)表于 2016年12月26日 16:38[回復]

            你這是基礎(chǔ)不過關(guān)啊… echo不能輸出數(shù)組,你想打印數(shù)組需要用print_r。

用戶評論頭像 逍遙網(wǎng)發(fā)表于 2016年04月06日 10:27[回復]

文章很不錯 歡迎訪問 逍遙網(wǎng)xywos.com

用戶評論頭像 阿里百秀發(fā)表于 2014年12月10日 20:00[回復]

博主怎么最近沒更新了

    用戶評論頭像 鄭曉發(fā)表于 2014年12月17日 09:12[回復]

    這兩天懶了,哈哈 :mrgreen:

用戶評論頭像 網(wǎng)絡(luò)兼職發(fā)表于 2014年12月09日 15:29[回復]

感覺博主蠻厲害的樣子

發(fā)表評論

change vcode