使用 pyparsing 可以实现相反的效果,如下所示:
from pyparsing import Suppress, replaceWith, makeHTMLTags, SkipTo
#...
removeText = replaceWith("")
scriptOpen, scriptClose = makeHTMLTags("script")
scriptBody = scriptOpen + SkipTo(scriptClose) + scriptClose
scriptBody.setParseAction(removeText)
data = (scriptBody).transformString(data)
我怎样才能保留标签的内容"table"
?
更新0:
我试过: # 只保留表格 tableOpen, tableClose = makeHTMLTags("table") tableBody = tableOpen + SkipTo(tableClose) + tableClose f = replaceWith(tableBody) tableBody.setParseAction(f) data = (tableBody).transformString(data)打印数据
我得到这样的东西......
garbages
<input type="hidden" name="cassstx" value="en_US:frontend"></form></td></tr></table></span></td></tr></table>
{<"table"> SkipTo:(</"table">) </"table">}
<div id="asbnav" style="padding-bottom: 10px;">{<"table"> SkipTo:(</"table">) </"table">}
</div>
even more garbages
更新 2:
谢谢马泰利。我需要的是:
from pyparsing import Suppress, replaceWith, makeHTMLTags, SkipTo
#...
data = 'before<script>ciao<table>buh</table>bye</script>after'
tableOpen, tableClose = makeHTMLTags("table")
tableBody = tableOpen + SkipTo(tableClose) + tableClose
thetable = (tableBody).searchString(data)[0][2]
print thetable