考慮以下HTML輸入:Python類HTMLParser的錯誤給予解析錯誤
<html>
<head>
<script>
function open_tools(tool_div)
{
document.getElementById("tool1").innerHTML = "<a href='javascript:void(0);' onclick=\"javascript:clos_tools('""');\"><img src='menu.gif' border='0' /></a>";
document.getElementById("tool").innerHTML = "<a href='javascript:void(0);' onclick=\"javascript:open_tools('""');\"><img src='plus.gif' border='0' /></a>";
}
</script>
</head>
<body />
</html>
爲了快速測試,假設你在 'test.html中' Python的外殼轉儲這個網站的數據,
>>> f = open('test.html', 'r')
>>> data = f.read()
>>> from HTMLParser import HTMLParser
>>> p = HTMLParser()
>>> p.feed(data)
Burrrppp ......與以下錯誤
File "lib\HTMLParser.py", line 155, in goahead
k = self.parse_starttag(i) File "lib\HTMLParser.py", line 235, in parse_starttag
endpos = self.check_for_whole_start_tag(i) File "lib\HTMLParser.py", line 319, in check_for_whole_start_tag
self.error("malformed start tag") File "lib\HTMLParser.py", line 115, in error
raise HTMLParseError(message, self.getpos()) HTMLParseError: malformed start tag, at line 7, column 88
我與這個錯誤過去混淆6個小時。這是我在裏面發現的HTMLParser.py代碼:
解析時,遇到腳本標記時,它設置cdata = true。 之後,它使用interesting_cdata= re.compile(r'<(/|\Z)')
正則表達式來找出script標籤的結束[內goahead()
]
不幸的是,現在看來,這是找到腳本標籤的末尾</a>
的function open_tools
而不是在</script>
第一條語句。然後它在功能的第二行中出現毛刺。
我不知道如何解決這個問題,並想到HTMLParser中的錯誤令人不安。誰能幫忙?
注:我是一個Python愛好者及以上與Python 2.6測試(窗口)
編輯:是的,它的工作原理與BeautifulSoup。但我有興趣知道正則表達式是否被破壞(以及如何修復)以及HTMLParser類的其他問題。在圖書館代碼的第一步卡住是令人沮喪的。關於PHP文檔的好處是能夠在官方文檔頁面上發表評論。同樣在msdn上也被支持。
不知道這一點的錯誤 - 但你試過用BeautifulSoup? – BeRecursive 2011-12-24 21:13:12
我可以完全解析片段可以用Python 2.7.2的'HTMLParser'。 – 2011-12-24 21:23:08
@larsmans:我已經在2.5-2.7,3.0-3.3上試過它,它只能在3.3(cpython-e0df57330b83)上運行,例如3.1 http://ideone.com/x4qB3 – jfs 2011-12-25 04:46:47