【问题标题】:Making BeautifulSoup ignore contents inside script tags让 BeautifulSoup 忽略脚本标签内的内容
【发布时间】:2010-12-16 12:28:03
【问题描述】:

我一直在尝试让 BeautifulSoup (3.1.0.1) 解析一个 html 页面,该页面有很多在标签内生成 html 的 javascript。 一个示例片段如下所示:

<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 上运行。

【问题讨论】:

标签: python beautifulsoup html-parsing


【解决方案1】:

这可行,但 BeautifulSoup 的重点是解析你扔给它的任何标签汤,即使它的格式非常糟糕。

【讨论】:

  • BeautifulSoup 在加载 html 时在 &lt;script&gt; 标签中阻塞 &lt;&gt; 时会怎样呢?对我来说,加载 html BeautifulSoup(badHtml) 时会发生此崩溃。
  • 那将是 BeautifulSoup 中的一个错误。
【解决方案2】:

恢复到 BeautifulSoup 3.0.7a 解决了这个问题以及 3.1.0.1 中的许多其他 html 奇怪问题。

【讨论】:

    【解决方案3】:

    我以前遇到过这种问题,我通常会用&lt;!--&lt;/script&gt; 替换每个出现的&lt;script--&gt;。这样一来,所有的&lt;script&gt;&lt;/script&gt; 标签都会被注释掉。

    【讨论】:

    • 好点,但如果脚本标签本身包含 将不起作用
    • 确实如此。我想你可以实现一个健全性检查,这样当遇到
    猜你喜欢
    • 1970-01-01
    • 2012-11-20
    • 2020-11-14
    • 1970-01-01
    • 2015-02-03
    • 2014-10-02
    • 1970-01-01
    • 2012-12-27
    • 2015-02-20
    相关资源
    最近更新 更多