从Python执行Javascript
我有使用xpath爬行的HTML网页。在etree.tostring
某个节点的给我这个字符串:
<script>
<!--
function escramble_758(){
var a,b,c
a='+1 '
b='84-'
a+='425-'
b+='7450'
c='9'
document.write(a+c+b)
}
escramble_758()
//-->
</script>
我只需要输出escramble_758()
。我可以编写一个正则表达式来弄清楚整个事情,但是我希望我的代码保持整洁。最好的选择是什么?
我正在浏览以下库,但没有看到确切的解决方案。他们中的大多数人都试图模仿浏览器,从而使蜗牛的速度变慢。
- http://code.google.com/p/python-spidermonkey/(清楚地说
it's not yet possible to call a function defined in Javascript
) - http://code.google.com/p/webscraping/(看不到任何Java脚本,我可能是错的)
- http://pypi.python.org/pypi/selenium(模拟浏览器)
编辑: 一个例子将是伟大的..(准系统将做)
-
使用PyV8,我可以做到这一点。但是,我必须替换为
document.write
,return
因为没有DOM,因此没有document
。import PyV8 ctx = PyV8.JSContext() ctx.enter() js = """ function escramble_758(){ var a,b,c a='+1 ' b='84-' a+='425-' b+='7450' c='9' document.write(a+c+b) } escramble_758() """ print ctx.eval(js.replace("document.write", "return "))
或者您可以创建一个模拟文档对象
class MockDocument(object): def __init__(self): self.value = '' def write(self, *args): self.value += ''.join(str(i) for i in args) class Global(PyV8.JSClass): def __init__(self): self.document = MockDocument() scope = Global() ctx = PyV8.JSContext(scope) ctx.enter() ctx.eval(js) print scope.document.value