标题 | php提取网页正文内容的例子 |
内容 | 因为难点在于如何去识别并保留网页中的文章部分,而且删除其它无用的信息,并且要做到通用化,不能像火车头那样根据目标站来制定采集规则,因为搜索引擎结果中有各种的网页。 抓回一个页面的数据,如何匹配出正文部分,郑晓在下班路上想了个思路是: 1. 提取出body标签部分–>剔除所有链接–>剔除所有script、注释–>剔除所有空白标签(包括标签内不含中文的)–>获取结果。 2. 直接匹配出非链接的、 符合在div、p、h标签中的中文部分??? 还是会有不少其它多余信息啊,比如底部信息等。。 如何搞?不知道大家有木有什么思路或建议? 这个类是从网上找到的一个php实现的提取网页正文部分的算法,郑晓在本地也测试了下,准确率非常高。 代码如下 <?php class readability { // 保存判定结果的标记位名称 const attr_content_score = contentscore; // dom 解析类目前只支持 utf-8 编码 const dom_default_charset = utf-8; // 当判定失败时显示的内容 const message_can_not_get = readability was unable to parse this page for content.; // dom 解析类(php5 已内置) protected $dom = null; // 需要解析的源代码 protected $source = ; // 章节的父元素列表 private $parentnodes = array(); // 需要删除的标签 // 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); // 需要删除的属性 private $junkattrs = array(style, class, onclick, onmouseover, align, border, margin); /** * 构造函数 * @param $input_char 字符串的编码。默认 utf-8,可以省略 */ function __construct($source, $input_char = utf-8) { $this->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 (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) { // ... } } /** * 预处理 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 <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 标签 * * @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; } /** * 根据评分获取页面主要内容的盒模型 * 判定算法来自: * 这里由郑晓博客转发 * @return domnode */ private function gettopbox() { // 获得页面所有的章节 $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); // 保存章节的父元素,以便下次快速获取 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; } } // 此时,$topbox 应为已经判定后的页面内容主元素 return $topbox; } /** * 获取 html 页面标题 * * @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; } /** * 获取页面的主要内容(readability 以后的内容) * * @return array */ public function getcontent() { if (!$this->dom) return false; // 获取页面标题 $contenttitle = $this->gettitle(); // 获取页面主内容 $contentbox = $this->gettopbox(); //check if we found a suitable top-box. if($contentbox === null) throw new runtimeexception(readability::message_can_not_get); // 复制内容到新的 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); // 多个数据,以数组的形式返回 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() { } } 使用起来也非常简单,实例化时传入网页的html源码和相应的编码,然后直接调用其getcontent方法即可返回提取到的正文部分,提取出的文章中可能还会含有少部分链接,可以自己后期再修改 |
随便看 |
|
在线学习网考试资料包含高考、自考、专升本考试、人事考试、公务员考试、大学生村官考试、特岗教师招聘考试、事业单位招聘考试、企业人才招聘、银行招聘、教师招聘、农村信用社招聘、各类资格证书考试等各类考试资料。