gpt4 book ai didi

python - <script> 标签和 HTMLParseError

转载 作者:太空宇宙 更新时间:2023-11-03 19:18:55 29 4
gpt4 key购买 nike

我试图用 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/

29 4 0