1

我正在创建一个从任何网页获取图像网址的代码,该代码在 python 中并使用 BeutifulSoup 和 httplib2。当我运行代码时,我得到下一个错误:

Look me http://movies.nytimes.com          (this line is printed by the code)
Traceback (most recent call last):
File "main.py", line 103, in <module>
visit(initialList,profundidad)
File "main.py", line 98, in visit
visit(dodo[indice], bottom -1)
File "main.py", line 94, in visit
getImages(w)
File "main.py", line 34, in getImages
iSoupList = BeautifulSoup(response, parseOnlyThese=SoupStrainer('img'))
File "/usr/local/lib/python2.6/dist-packages/BeautifulSoup.py", line 1499, in __init__
BeautifulStoneSoup.__init__(self, *args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/BeautifulSoup.py", line 1230, in __init__
self._feed(isHTML=isHTML)
File "/usr/local/lib/python2.6/dist-packages/BeautifulSoup.py", line 1263, in _feed
self.builder.feed(markup)
File "/usr/lib/python2.6/HTMLParser.py", line 108, in feed
self.goahead(0)
File "/usr/lib/python2.6/HTMLParser.py", line 148, in goahead
k = self.parse_starttag(i)
File "/usr/lib/python2.6/HTMLParser.py", line 226, in parse_starttag
endpos = self.check_for_whole_start_tag(i)
File "/usr/lib/python2.6/HTMLParser.py", line 301, in check_for_whole_start_tag
self.error("malformed start tag")
File "/usr/lib/python2.6/HTMLParser.py", line 115, in error
raise HTMLParseError(message, self.getpos())
HTMLParser.HTMLParseError: malformed start tag, at line 942, column 118

有人可以向我解释如何修复或排除错误

4

3 回答 3

4

您使用的是最新版本的 BeautifulSoup 吗?
这似乎是 3.1.x 版的一个已知问题,因为它开始使用新的解析器(HTMLParser,而不是 SGMLParser),它在处理格式错误的 HTML 时要差得多。您可以在BeautifulSoup 网站上找到更多信息。
作为一种快速解决方案,您可以简单地使用旧版本 ( 3.0.7a )。

于 2009-07-08T20:46:06.153 回答
2

要专门捕获该错误,请将您的代码更改为如下所示:

try:
    iSoupList = BeautifulSoup(response, parseOnlyThese=SoupStrainer('img'))

except HTMLParseError:
    #Do something intelligent here

这里有一些关于 Python 的 try except 块的更多阅读:http: //docs.python.org/tutorial/errors.html

于 2009-07-08T19:20:53.143 回答
0

当我的HTML 文档中有字符串=&时,我得到了那个错误。当我替换该字符串(在我的情况下为=and)时,我不再收到该解析错误。

于 2009-12-03T22:34:07.397 回答