php提取網(wǎng)頁(yè)正文內(nèi)容的例子

字號(hào):


    因?yàn)殡y點(diǎn)在于如何去識(shí)別并保留網(wǎng)頁(yè)中的文章部分,而且刪除其它無用的信息,并且要做到通用化,不能像火車頭那樣根據(jù)目標(biāo)站來制定采集規(guī)則,因?yàn)樗阉饕娼Y(jié)果中有各種的網(wǎng)頁(yè)。
    抓回一個(gè)頁(yè)面的數(shù)據(jù),如何匹配出正文部分,鄭曉在下班路上想了個(gè)思路是:
    1. 提取出body標(biāo)簽部分–>剔除所有鏈接–>剔除所有script、注釋–>剔除所有空白標(biāo)簽(包括標(biāo)簽內(nèi)不含中文的)–>獲取結(jié)果。
    2. 直接匹配出非鏈接的、 符合在div、p、h標(biāo)簽中的中文部分???
    還是會(huì)有不少其它多余信息啊,比如底部信息等。。 如何搞?不知道大家有木有什么思路或建議?
    這個(gè)類是從網(wǎng)上找到的一個(gè)php實(shí)現(xiàn)的提取網(wǎng)頁(yè)正文部分的算法,鄭曉在本地也測(cè)試了下,準(zhǔn)確率非常高。
    代碼如下
    <?php
    class readability {
    // 保存判定結(jié)果的標(biāo)記位名稱
    const attr_content_score = contentscore;
    // dom 解析類目前只支持 utf-8 編碼
    const dom_default_charset = utf-8;
    // 當(dāng)判定失敗時(shí)顯示的內(nèi)容
    const message_can_not_get = readability was unable to parse this page for content.;
    // dom 解析類(php5 已內(nèi)置)
    protected $dom = null;
    // 需要解析的源代碼
    protected $source = ;
    // 章節(jié)的父元素列表
    private $parentnodes = array();
    // 需要?jiǎng)h除的標(biāo)簽
    // note: added extra tags from
    private $junktags = array(style, form, iframe, script, button, input, textarea,
    noscript, select, option, object, applet, basefont,
    bgsound, blink, canvas, command, menu, nav, datalist,
    embed, frame, frameset, keygen, label, marquee, link);
    // 需要?jiǎng)h除的屬性
    private $junkattrs = array(style, class, onclick, onmouseover, align, border, margin);
    /**
    * 構(gòu)造函數(shù)
    * @param $input_char 字符串的編碼。默認(rèn) utf-8,可以省略
    */
    function __construct($source, $input_char = utf-8) {
    $this->source = $source;
    // dom 解析類只能處理 utf-8 格式的字符
    $source = mb_convert_encoding($source, 'html-entities', $input_char);
    // 預(yù)處理 html 標(biāo)簽,剔除冗余的標(biāo)簽等
    $source = $this->preparsource($source);
    // 生成 dom 解析類
    $this->dom = new domdocument('1.0', $input_char);
    try {
    //libxml_use_internal_errors(true);
    // 會(huì)有些錯(cuò)誤信息,不過不要緊 :^)
    if (encoding='.readability::dom_default_charset.'>'.$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) {
    // ...
    }
    }
    /**
    * 預(yù)處理 html 標(biāo)簽,使其能夠準(zhǔn)確被 dom 解析類處理
    *
    * @return string
    */
    private function preparsource($string) {
    // 剔除多余的 html 編碼標(biāo)記,避免解析出錯(cuò)
    preg_match(/charset=([\w|\-]+);?/, $string, $match);
    if (isset($match[1])) {
    $string = preg_replace(/charset=([\w|\-]+);?/, , $string, 1);
    }
    // replace all doubled-up <br> tags with <p> tags, and remove fonts.
    $string = preg_replace(/<br\/?>[ \r\n\s]*<br\/?>/i, </p><p>, $string);
    $string = preg_replace(/<\/?font[^>]*>/i, , $string);
    // @see
    // - from
    $string = preg_replace(#<script(.*?)>(.*?)</script>#is, , $string);
    return trim($string);
    }
    /**
    * 刪除 dom 元素中所有的 $tagname 標(biāo)簽
    *
    * @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ù)評(píng)分獲取頁(yè)面主要內(nèi)容的盒模型
    * 判定算法來自:
    * 這里由鄭曉博客轉(zhuǎn)發(fā)
    * @return domnode
    */
    private function gettopbox() {
    // 獲得頁(yè)面所有的章節(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 <p>'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
    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;
    }
    }
    // 此時(shí),$topbox 應(yīng)為已經(jīng)判定后的頁(yè)面內(nèi)容主元素
    return $topbox;
    }
    /**
    * 獲取 html 頁(yè)面標(biāo)題
    *
    * @return string
    */
    public function gettitle() {
    $split_point = ' - ';
    $titlenodes = $this->dom->getelementsbytagname(title);
    if ($titlenodes->length
    && $titlenode = $titlenodes->item(0)) {
    // @see
    $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;
    }
    /**
    * 獲取頁(yè)面的主要內(nèi)容(readability 以后的內(nèi)容)
    *
    * @return array
    */
    public function getcontent() {
    if (!$this->dom) return false;
    // 獲取頁(yè)面標(biāo)題
    $contenttitle = $this->gettitle();
    // 獲取頁(yè)面主內(nèi)容
    $contentbox = $this->gettopbox();
    //check if we found a suitable top-box.
    if($contentbox === null)
    throw new runtimeexception(readability::message_can_not_get);
    // 復(fù)制內(nèi)容到新的 domdocument
    $target = new domdocument;
    $target->appendchild($target->importnode($contentbox, true));
    // 刪除不需要的標(biāo)簽
    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);
    // 多個(gè)數(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() { }
    }
    使用起來也非常簡(jiǎn)單,實(shí)例化時(shí)傳入網(wǎng)頁(yè)的html源碼和相應(yīng)的編碼,然后直接調(diào)用其getcontent方法即可返回提取到的正文部分,提取出的文章中可能還會(huì)含有少部分鏈接,可以自己后期再修改