LMLPHP后院

写网页爬虫遇到标签匹配难题技术

maybe yes 发表于 2015-02-02 13:22

前段时间写优化网页节点的程序时,遇到了标签匹配的难题。在匹配图片标签时,由于标签里面的 JavaScript 代码中含有大于号“>”导致无法匹配完整的标签内容。将这样的问题分享出来,不知道百度啊他们的爬虫是如何处理这样的问题的。请看下面的代码

<!-- HTML DOCUMENT -->
<IMG onmousewheel="return imgzoom(this);" onmouseover="if(this.width>screen.width*0.7) {this.resized=true; this.width=screen.width*0.7; this.style.cursor='hand'; this.alt='Click here to open new window\nCTRL+Mouse wheel to zoom in/out';}" onclick="if(!this.resized) {return true;} else {window.open(this.src);}" alt="" src="http://xxx.com/upload/20080226120423341.gif" onload="if(this.width>screen.width*0.7) {this.resized=true; this.width=screen.width*0.7; this.alt='Click here to open new window\nCTRL+Mouse wheel to zoom in/out';}" border=0>

针对上面的 HTML 代码,用一般的正则是没有办法将整个图片标签匹配下来的。因为标签内部的 JavaScript 中含有大于号 > 或小于号 < 。找了很多资料,仍没有发现一劳永逸的方法,很多网友说这种情况只能特定处理,并且这个情况特殊,代码中的大于号没有转义是不符合 WEB 2.0 的规范的。想了很多方法,依然写不出能够很好的处理引号中的内容不匹配并且能够很好的处理引号的配对关系的正则,不知道哪位高手能够很好的解决这样的问题,欢迎留言。然后,我就写了个特定的处理方案,代码如下:

<?php

$str = '<IMG onmousewheel="return imgzoom(this);" onmouseover="if(this.width>screen.width*0.7) {this.resized=true; this.width=screen.width*0.7; this.style.cursor=\'hand\'; this.alt=\'Click here to open new window\nCTRL+Mouse wheel to zoom in/out\';}" onclick="if(!this.resized) {return true;} else {window.open(this.src);}" alt="" src="http://xxx.com/upload/20080226120423341.gif" onload="if(this.width>screen.width*0.7) {this.resized=true; this.width=screen.width*0.7; this.alt=\'Click here to open new window\nCTRL+Mouse wheel to zoom in/out\';}" border=0>';

preg_match('/<img.*?(?<!width)>/i', $str, $matches, PREG_OFFSET_CAPTURE);

上面的代码针对这样的标签做了特殊处理,判断的是大于号 > 的前面不能有 width。当今的网页很难做到每个地方都完全的遵守 WEB 2.0 的规范,一个成熟的网页分析工具,这样的问题是必须要解决的,也许通过正则真的做不到,目前想到的比较好的方式是使用 DOMDOCUMENT 来渲染。

相关文章
2024-04-27 07:55:40 1714175740 0.029060