时间:2012-05-05 12:03:24

标签: python beautifulsoup

我正在尝试用BeautifulSoup解析html并得到奇怪的错误。 这是重现问题的最小代码。 (Windows 7 32位,ActivePython 2.7)。

from bs4 import BeautifulSoup
s = """
<html>
<script>
var pstr = "<li><font color='blue'>1</font></li>";
for(var lc=0;lc<o.length;lc++){}
</script>
</html>
"""
p = BeautifulSoup(s)

回溯:

Traceback (most recent call last):
  File "<pyshell#69>", line 1, in <module>
    p = BeautifulSoup(s)
  File "C:\Python27\lib\site-packages\bs4\__init__.py", line 168, in __init__
    self._feed()
  File "C:\Python27\lib\site-packages\bs4\__init__.py", line 181, in _feed
    self.builder.feed(self.markup)
  File "C:\Python27\lib\site-packages\bs4\builder\_htmlparser.py", line 56, in feed
    super(HTMLParserTreeBuilder, self).feed(markup)
  File "C:\Python27\lib\HTMLParser.py", line 108, in feed
    self.goahead(0)
  File "C:\Python27\lib\HTMLParser.py", line 148, in goahead
    k = self.parse_starttag(i)
  File "C:\Python27\lib\HTMLParser.py", line 229, in parse_starttag
    endpos = self.check_for_whole_start_tag(i)
  File "C:\Python27\lib\HTMLParser.py", line 304, in check_for_whole_start_tag
    self.error("malformed start tag")
  File "C:\Python27\lib\HTMLParser.py", line 115, in error
    raise HTMLParseError(message, self.getpos())
HTMLParseError: malformed start tag, at line 5, column 25

如果删除以'var pstr = ...'开头的行,则解析将完美运行。有没有办法像这样得到正确的html代码解析?

1 个答案:

答案 0 :(得分:1)

您可以尝试旧版本的BS或安装其他解析器。请参阅BeautifulSoup网站上有关“you need a parser”和“installing a parser”的文档。

您当前的代码适用于Python 2.7和BS3:

from BeautifulSoup import BeautifulSoup
s = """
<html>
<script>
var pstr = "<li><font color='blue'>1</font></li>";
for(var lc=0;lc<o.length;lc++){}
</script>
</html>
"""
p = BeautifulSoup(s)

print p.find('script').text

并生成此输出:

var pstr = "<li><font color='blue'>1</font></li>";
for(var lc=0;lc<o.length>