疑似BUG:Python SGMLParser处理html中的javascript失当

疑似BUG:SGMLParser处理html标签中的javascript时特定情况下失当
库:Python2.4/2.5的sgmllib库
牵连库: Beautiful Soup version 3.0.5以及3.0.3版本

举例:
html代码如下定义:
None.gif     sExceptionHtml  =   ''' <span>出错的html标签:</span><div id='error'>
None.gif<img src="http://www.onejoo.com/daylife_media/images/articlesid/1.jpg" border="0" 
None.gif   οnmοuseοver="if(this.width>screen.width*0.7) {this.resized=true; this.width=screen.width*0.7;
None.gif           this.style.cursor='hand';this.alt='Click here to open new window\nCTRL+Mouse wheel to zoom in/out';}"
None.gif   οnlοad="if(this.width>screen.width*0.7) {this.resized=true; this.width=screen.width*0.7;
None.gif           this.alt='Click here to open new window\nCTRL+Mouse wheel to zoom in/out';}"
None.gif/>寒!<br /></div>
'''
这个img标签有两个属性:onload和onmouseover,里面都写的是javascript代码,并且出现了“>”判断符号。当让SGMLParser处理这种html代码时,它错误地解析了。
对于上面的html代码,会得到如下处理过后的img:
<img src=" http://www.onejoo.com/daylife_media/images/articlesid/1.jpg" border="0" οnmοuseοver="if(this.width&gt;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
CTRL+Mouse wheel to zoom in/out';}" /> 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
CTRL+Mouse wheel to zoom in/out';}"
   οnlοad="if(this.width>screen.width*0.7) {this.resized=true; this.width=screen.width*0.7;
           this.alt='Click here to open new window
CTRL+Mouse wheel to zoom in/out';}"
/>

显然,onmouseover的东西乱掉了。很有可能就是javascript中的“this.width>screen.width*0.7”中“>”被误当作html标签的结束符处理了。
如果确实是这样,倒也可以理解,只是咱们就受累些,之前提前清除onload属性和onmouseover属性吧,省得里面的javascript干扰。
    page_content = re.sub('οnlοad=\"\s*[^\"]*\"','',page_content)
    page_content = re.sub('οnmοuseοver=\"\s*[^\"]*\"','',page_content)

牵连影响:并因此影响到了 Beautiful Soup对html的解析。

你可以测试如下代码,可以重现此问题:
None.gif # coding=utf-8
None.gif
import  sys, os, urllib, re
None.gif
from  sgmllib  import  SGMLParser
None.gif
from  BeautifulSoup  import  BeautifulSoup
None.gif
None.gif
def  replaceHTMLTag(content):
None.gif    htmlextractor 
=  html2txt()
None.gif    
#  调用定义在 SGMLParser 中的 feed 方法,将 HTML 内容放入分析器中。
None.gif
    htmlextractor.feed(content)
None.gif    
#  应该 close 您的分析器对象,但出于不同的原因。feed 方法不保证对传给它的全部 HTML 进行处理,
None.gif
     #  它可能会对其进行缓冲处理,等待接收更多的内容。一旦没有更多的内容,应调用 close 来刷新缓冲区,并且强制所有内容被完全处理。
None.gif
    htmlextractor.close()
None.gif    
#  一旦分析器被 close,分析过程也就结束了。htmlextractor.urls 中包含了在 HTML 文档中所有的链接 URL。
None.gif

None.gif
     return  htmlextractor.text
None.gif
None.gif
#  为了从 HTML 文档中提取数据,将 SGMLParser 类进行子类化,然后对想要捕捉的标记或实体定义方法。
None.gif
class  html2txt(SGMLParser):
None.gif     
def   __init__ (self):
None.gif        SGMLParser.
__init__ (self)
None.gif        self._result 
=  []
None.gif        self._data_stack 
=  []
None.gif
None.gif     
'''
None.gif     reset 由 SGMLParser 的 __init__ 方法来调用,也可以在创建一个分析器实例时手工来调用。
None.gif     所以如果您需要做初始化,在 reset 中去做,而不要在 __init__ 中做。
None.gif     这样当某人重用一个分析器实例时,会正确地重新初始化。
None.gif     
'''
None.gif     
def  reset(self):
None.gif         self.text 
=   ''
None.gif         self.inbody 
=  True
None.gif         SGMLParser.reset(self)
None.gif     
def  handle_data(self,text):
None.gif         
if  self.inbody:
None.gif             self.text 
+=  text
None.gif     
def  _write(self, d):
None.gif        
if  len(self._data_stack)  <   2 :
None.gif            target 
=  self._result
None.gif        
else :
None.gif            target 
=  self._data_stack[ - 1 ]
None.gif        
if  type(d)  in  (list, tuple):
None.gif            target 
+=  d
None.gif        
else :
None.gif            target.append(str(d))
None.gif
None.gif     
def  start_head(self,text):
None.gif         self.inbody 
=  False
None.gif     
def  end_head(self):
None.gif         self.inbody 
=  True
None.gif     
def  _get_result(self):
None.gif        
return   "" .join(self._result).strip()
None.gif
None.gif     result 
=  property(_get_result)
None.gif
None.gif
None.gif
#  应用入口        
None.gif
if   __name__   ==   ' __main__ ' :
None.gif
None.gif    sExceptionHtml 
=   ''' <span>出错的html标签:</span><div id='error'>
None.gif<img src="http://www.onejoo.com/daylife_media/images/articlesid/1.jpg" border="0" 
None.gif   οnmοuseοver="if(this.width>screen.width*0.7) {this.resized=true; this.width=screen.width*0.7;
None.gif           this.style.cursor='hand';this.alt='Click here to open new window\nCTRL+Mouse wheel to zoom in/out';}"
None.gif   οnlοad="if(this.width>screen.width*0.7) {this.resized=true; this.width=screen.width*0.7;
None.gif           this.alt='Click here to open new window\nCTRL+Mouse wheel to zoom in/out';}"
None.gif/>寒!<br /></div>
'''
None.gif    soup 
=  BeautifulSoup(sExceptionHtml,fromEncoding = ' gbk ' )
None.gif    body_content 
=  soup.findAll( ' div ' ,attrs = { ' id '  : re.compile( " ^error " )})
None.gif    
print   ' ---------------------- '
None.gif    
print  body_content[0]
None.gif    
print   ' ---------------------- '
None.gif    
None.gif    sExceptionHtml 
=  replaceHTMLTag(sExceptionHtml).strip()
None.gif    
print   ' ---------------------- '
None.gif    
print  sExceptionHtml
None.gif    
print   ' ----------------------- '
None.gif    


结论:不是什么严重问题。只是当html代码中在标签的属性中写javascript时,需要注意到此种特性,如果出现“>”符号,就会导致SGMLParser以及使用SGMLParser的其他库解析失当。zhengyun 20080115

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值