BUG触发时的完整报错内容(本地无关路径用已经用 **** 隐去):

**************\lib\site-packages\bs4\builder\_htmlparser.py:78: UserWarning: unknown status keyword 'end ' in marked section
warnings.warn(msg)
Traceback (most recent call last):
File "**************/test.py", line 5, in <module>
bs = BeautifulSoup(html, 'html.parser')
File "**************\lib\site-packages\bs4\__init__.py", line 281, in __init__
self._feed()
File "**************\lib\site-packages\bs4\__init__.py", line 342, in _feed
self.builder.feed(self.markup)
File "**************\lib\site-packages\bs4\builder\_htmlparser.py", line 247, in feed
parser.feed(markup)
File "D:\Program Files\Python37\lib\html\parser.py", line 111, in feed
self.goahead(0)
File "D:\Program Files\Python37\lib\html\parser.py", line 179, in goahead
k = self.parse_html_declaration(i)
File "D:\Program Files\Python37\lib\html\parser.py", line 264, in parse_html_declaration
return self.parse_marked_section(i)
File "D:\Program Files\Python37\lib\_markupbase.py", line 160, in parse_marked_section
if not match:
UnboundLocalError: local variable 'match' referenced before assignment

在解析HTML时,标签开始部分使用形如 <!-[if IE eq 9]> 的浏览器判断标识符,结束时结束标签<![end if]->(正确的开始和结束标签应该为<!--[if IE 9]><![endif]-->)无法正常匹配关闭即可触发。

触发BUG的示例代码如下:

from bs4 import BeautifulSoup

html = """
<!-[if IE eq 9]>
<a href="https://www.shwww.net/">https://www.shwww.net/</a>
<![end if]->
""" bs = BeautifulSoup(html, 'html.parser')

在 Python 3.7.0 版本中,触发BUG部分的代码存在于 \Lib\_markupbase.py 中的 146 行的 parse_marked_section 方法,该方法代码如下:

https://github.com/python/cpython/blob/bb9ddee3d4e293f0717f8c167afdf5749ebf843d/Lib/_markupbase.py#L160

    def parse_marked_section(self, i, report=1):
rawdata= self.rawdata
assert rawdata[i:i+3] == '<![', "unexpected call to parse_marked_section()"
sectName, j = self._scan_name( i+3, i )
if j < 0:
return j
if sectName in {"temp", "cdata", "ignore", "include", "rcdata"}:
# look for standard ]]> ending
match= _markedsectionclose.search(rawdata, i+3)
elif sectName in {"if", "else", "endif"}:
# look for MS Office ]> ending
match= _msmarkedsectionclose.search(rawdata, i+3)
else:
self.error('unknown status keyword %r in marked section' % rawdata[i+3:j])
if not match:
return -1
if report:
j = match.start(0)
self.unknown_decl(rawdata[i+3: j])
return match.end(0)

由于错误的HTML代码未正确关闭,使得流程判断既没有进入 if sectName in {"temp", "cdata", "ignore", "include", "rcdata"}:

elif sectName in {"if", "else", "endif"}: ,而是报出一个错误 UserWarning: unknown status keyword 'end ' in marked section warnings.warn(msg) 后执行到 if not match ,而此时 match 未申明,故而触发错误。

此BUG存在于多个Python版本中,修复方法,在 if sectName in {"temp", "cdata", "ignore", "include", "rcdata"}: 之前预定义一个match变量即可:

https://github.com/python/cpython/blob/bb9ddee3d4e293f0717f8c167afdf5749ebf843d/Lib/_markupbase.py#L152

    def parse_marked_section(self, i, report=1):
rawdata= self.rawdata
assert rawdata[i:i+3] == '<![', "unexpected call to parse_marked_section()"
sectName, j = self._scan_name( i+3, i )
if j < 0:
return j
match = None
if sectName in {"temp", "cdata", "ignore", "include", "rcdata"}:
# look for standard ]]> ending
match= _markedsectionclose.search(rawdata, i+3)
elif sectName in {"if", "else", "endif"}:
# look for MS Office ]> ending
match= _msmarkedsectionclose.search(rawdata, i+3)
else:
self.error('unknown status keyword %r in marked section' % rawdata[i+3:j])
if not match:
return -1
if report:
j = match.start(0)
self.unknown_decl(rawdata[i+3: j])
return match.end(0)

_markupbase.py if not match: UnboundLocalError: local variable 'match' referenced before assignment,分析Python 库 html.parser 中存在的一个解析BUG的更多相关文章

  1. RDO Stack Exception: UnboundLocalError: local variable 'logFile' referenced before assignment

    Issue: When you install RDO stack on CentOS, you may encounter following error. Error: [root@localho ...

  2. UnboundLocalError: local variable 'range' referenced before assignment

    1. 报错信息 UnboundLocalError: local variable 'range' referenced before assignment 2. 代码 class Car(): &q ...

  3. 洗礼灵魂,修炼python(23)--自定义函数(4)—闭包进阶问题—>报错UnboundLocalError: local variable 'x' referenced before assignment

    闭包(lexical closure) 什么是闭包前面已经说过了,但是由于遗留问题,所以单独作为一个章节详解讲解下 不多说,看例子: def funx(x): def funy(y): return ...

  4. 变量引用的错误:UnboundLocalError: local variable 'range' referenced before assignment

    class Battery(): """一次模拟电瓶汽车的简单尝试""" def __init__(self,battery_size = ...

  5. 出现UnboundLocalError: local variable 'a' referenced before assignment异常的情况与解决方法

    出现UnboundLocalError: local variable ‘a’ referenced before assignment异常的情况与解决方法字面意思:局部变量赋值前被引用原因:局部变量 ...

  6. 全局变量报错:UnboundLocalError: local variable 'l' referenced before assignment

    总结: 内部函数,不修改全局变量可以访问全局变量 内部函数,修改同名全局变量,则python会认为它是一个局部变量 在内部函数修改同名全局变量之前调用变量名称(如print sum),则引发Unbou ...

  7. python:UnboundLocalError: local variable 'xxx' referenced before assignment

    近来一直都在学习python语言,偶然在伯乐在线看到2017年京东C/C++的面试题.就打算用python+ST3 IDE顺便敲下面试题代码. 原题 C语言: #include <stdio.h ...

  8. UnboundLocalError: local variable ‘xxx‘ referenced before assignment

    原因 在Python函数中调用了某个和全局变量同名的局部变量,导致编译器不知道此时使用的是全局变量还是局部变量 a = 3 def func(): a+=3 func() UnboundLocalEr ...

  9. UnboundLocalError: local variable 'f' referenced before assignment

    参考方案链接: 1.http://blog.chinaunix.net/uid-631981-id-3766212.html 2.http://blog.sina.com.cn/s/blog_4b9e ...

随机推荐

  1. 幻世(OurDream)TM 2D图形引擎开通捐赠渠道

    为了支持幻世(OurDream)TM 2D图形引擎更好的发展,同一时候也是为了给希望支持引擎发展的朋友一个安全快捷的渠道,Lizcst Software Lab于今日正式在官方旗舰店增设了一个捐赠捐款 ...

  2. 64位BASM学习随笔(一)

     64位BASM学习随笔(一) Delphi的BASM一直是我最喜爱的内嵌汇编语言,同C/C++的内联汇编相比,它更方便,更具灵活性,由于C/C++的内联汇编仅仅能是或插入式的汇编代码,函数花括号 ...

  3. 飞信php接口 web service

    <?php /**     ┃      ┃   code is far away from bug with the animal protecting     ┃      ┃  神兽保佑, ...

  4. 虚函数的特点就是执行的时候会下降到子类去执行同名覆盖函数 good

    var t: TBitBtn;begin t:=TBitBtn.Create(nil); t.Name:='BitBtn100'; t.parent :=Self; // 这里下断点end; 一路跟踪 ...

  5. 《TCP/IP具体解释》读书笔记(21章)-TCP的超时与重传

    TCP提供可靠的运输层. 它使用的方法之中的一个就是确认从还有一端收到的数据.但数据和确认都有可能会丢失.TCP通过在发送时设置一个定时器来解决这样的问题.假设当定时器溢出时还没有收到确认,它就重传该 ...

  6. PCB .NET连接MySQL与Oracle DLL文分享件 MySql.Data,Oracle.ManagedDataAccess

    虽然我们C#对SQL SERVER天然的支持,但对于C#要连接MYSQL或Oracle就不同了, 需要用到第3方组件才行,本文将2个组件连接数据库代码与DLL下载地址贴出. 一.C#连接MYSQL   ...

  7. Necklace of Beads(polya定理)

    http://poj.org/problem?id=1286 题意:求用3种颜色给n个珠子涂色的方案数.polya定理模板题. #include <stdio.h> #include &l ...

  8. php 原生简版日志导出

    <?phpfunction writeLog($msg){ $logFile = date('Y-m-d').'.txt'; $msg = date('Y-m-d H:i:s').' >& ...

  9. 洛谷 P2986 [USACO10MAR]Great Cow Gat…(树形dp+容斥原理)

    P2986 [USACO10MAR]伟大的奶牛聚集Great Cow Gat… 题目描述 Bessie is planning the annual Great Cow Gathering for c ...

  10. golang单点推送

    package main import ( "encoding/json" "flag" "fmt" "log" &qu ...