python - <script> 标签和 HTMLParseError

标签 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代码?

最佳答案

您可以尝试旧版本的 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>

关于python - &lt;script&gt; 标签和 HTMLParseError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10461665/

相关文章:

python - 如何使用 Selenium 或 BeautifulSoup 遍历这些 javascript 链接?

python - 如何将抓取的数据保存到 CSV 文件中?

python - 你能从 Anaconda 而不是 pip 安装 numpy_financial 吗?

python - 为什么 type(x) 和 print(type(x) 在 python 中显示的结果略有不同?

python - 从 Matlab 到 Numpy 的矩阵乘法转换

Python Beautiful Soup Table 数据抓取特定 TD 标签

python - Google Scrape with Python 中的结果数量错误

python - 在 Python 中检查属于斐波那契数列的输入

python - 如何将 ArangoDB 与灯泡和 rexster 一起使用?

python - 使用 beautifulsoup,如何从页面中抓取表头