zl程序教程

您现在的位置是:首页 >  后端

当前栏目

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

PythonJavaScriptBUGHTML 处理 疑似
2023-09-14 08:58:22 时间
疑似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    margin:0px;padding:0px;">None.gif           this.style.cursor=hand;this.alt=Click here to open new window\nCTRL+Mouse wheel to zoom in/out;}"
None.gif   onload="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" margin:0px;padding:0px;color:rgb(64,50,38);font-family:verdana, ms song, 宋体, Arial, 微软雅黑, Helvetica, sans-serif;font-size:12px;line-height:24px;background-color:rgb(255,255,255);">           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;}"
   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
CTRL+Mouse wheel to zoom in/out;}"
/
显然,onmouseover的东西乱掉了。很有可能就是javascript中的“this.width screen.width*0.7”中“ ”被误当作html标签的结束符处理了。
如果确实是这样,倒也可以理解,只是咱们就受累些,之前提前清除onload属性和onmouseover属性吧,省得里面的javascript干扰。
    page_content = re.sub(onload=\"\s*[^\"]*\",,page_content)
    page_content = re.sub( "\s*[^\"]*\",,page_content)

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

你可以测试如下代码,可以重现此问题:
None.gif#coding=utf-8
None.gifimport sys, os, urllib, re
None.giffrom sgmllib import SGMLParser
None.giffrom BeautifulSoup import BeautifulSoup
None.gif
None.gifdef 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.gifclass 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.gifif __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    margin:0px;padding:0px;">None.gif           this.style.cursor=hand;this.alt=Click here to open new window\nCTRL+Mouse wheel to zoom in/out;}"
None.gif   onload="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


python接口自动化(三十一)--html测试报告通过邮件发出去——下(详解) 本篇总结了 QQ (SSL)邮箱和 163(非SSL) 邮箱发送邮件,专治各种不行,总之看完这篇以后麻麻再也不用担心我的邮件收不到了。以下代码兼容 python2 和 python3,运行无异常,放心大胆使用。
python接口自动化(三十)--html测试报告通过邮件发出去——中(详解) 上一篇,我们虽然已经将生成的最新的测试报告发出去了,但是MIMEText 只能发送正文,无法带附件,因此我还需要继续改造我们的代码,实现可以发送带有附件的邮件。发送带附件的需要导入另外一个模块 MIMEMultipart。还有就是测 试负责人不止一个人,需要将测试报告发给多个人,也就是多个收件人。这篇主要是围绕这两个主题进行讲解的。
python接口自动化(二十九)--html测试报告通过邮件发出去——上(详解) 前边几篇,已经教小伙伴们掌握了如何生成HTML的测试报告,那么生成测试报告,我们也不能放在那里不管了,这样即使你报告在漂亮,领导也看不到。因此如果想向领导汇报工作,不仅需要提供更直观的测试报告。而是我们需要将生 成测试报告发个相关的负责人,需要他们看一下测试结果,把控一下项目的接口有风险,会不会影响项目进度等等一些事吧。
python接口自动化(二十八)--html测试 报告——下(详解) 上一篇我们批量执行完用例后,已经生成的测试报告是生成 HTML 格式的。但是我们可以看出那个官方的测试报告既不美观也不大方,我们这里需要优化一下,优化的让人赏心悦目,就和看到一个美女一样看了一眼,忍不住回头再多看一眼 - _ - 并且把上一篇遇到的问题列举解决一下。
郑昀 ☑移动数据业务 times;6年 ☑语义聚合 times;4年 ☑O2O times;5年的一个老兵。