让BeautifulSoup忽略script标签内的内容

1 投票
3 回答
1877 浏览
提问于 2025-04-15 15:59

我一直在尝试使用BeautifulSoup(3.1.0.1)来解析一个包含很多JavaScript的网页,这些JavaScript会在标签内生成HTML。
其中一个示例片段看起来像这样:

<html><head><body><div>
<script type='text/javascript'>

if(ii > 0) {
html += '<span id="hoverMenuPosSepId" class="hoverMenuPosSep">|</span>'
}
html += 
'<div class="hoverMenuPos" id="hoverMenuPosId" onMouseOver=\"menuOver_3821();\" ' +
'onMouseOut=\"menuOut_3821();\">';
if (children[ii].uri == location.pathname) {
html += '<a class="hiHover" href="' +  children[ii].uri + '" ' + onClick + '>';
} else {
html += '<a class="hover" href="' +  children[ii].uri + '" ' + onClick + '>';
}
html += children[ii].name + '</a></div>';
}
}          
hp = document.getElementById("hoverpopup_3821");
hp.style.top = (parseInt(hoveritem.offsetTop) + parseInt(hoveritem.offsetHeight)) + "px";
hp.style.visibility = "Visible";
hp.innerHTML = html;
}
return false;
}
function menuOut_3821() {
timeOn_3821 =  setTimeout("showSelected_3821()",  1000)             
}
var timeOn_3821 = null;
function menuOver_3821() {
clearTimeout(timeOn_3821)
}   
function showSelected_3821() {
showChildrenMenu_3821( 
document.getElementById("flatMenuItemAnchor" + selectedPageId), selectedPageId);
}
</script>
</body>
</html>

但是,BeautifulSoup似乎无法处理这个问题,并且对“格式错误的开始标签”发出了警告,问题出在onMouseOver=**\"**menuOver_3821();\"附近。
它似乎在尝试解析JavaScript在脚本块中生成的XML内容?!

有没有办法让BeautifulSoup忽略脚本标签里的内容呢?

我看到有人建议使用lxml,但我不能使用,因为它必须在Google AppEngine上运行。

3 个回答

0

这样做是可以的,但BeautifulSoup的主要功能就是解析你给它的各种标签,即使这些标签的格式非常糟糕也没关系。

0

我以前也遇到过这种问题,通常我会把每个出现的 <script 替换成 <!--,把 </script> 替换成 -->。这样一来,所有的 <script></script> 标签就都变成了注释,不会被执行。

1

把BeautifulSoup换回3.0.7a版本解决了这个问题,还有很多其他的HTML小问题,这些问题在3.1.0.1版本上都处理得不好。

撰写回答