从Python执行Javascript

2024-09-25 08:26:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我有使用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()的输出。我可以编写一个regex来解决整个问题,但我希望我的代码保持整洁。最好的选择是什么?

我正在快速浏览下面的库,但没有找到确切的解决方案。他们中的大多数人都试图模仿浏览器,使事情变得缓慢。

编辑:一个例子会很棒。。(赤骨就行了)


Tags: pypicomhttp网页节点htmlgooglescript
3条回答

PyV8的另一个解决方案似乎是未维护的,并且依赖于旧版本的libv8。

PyMiniRacer它是v8引擎的包装器,它与新版本一起工作,并被积极维护。

pip install py-mini-racer

from py_mini_racer import py_mini_racer
ctx = py_mini_racer.MiniRacer()
ctx.eval("""
function escramble_758(){
    var a,b,c
    a='+1 '
    b='84-'
    a+='425-'
    b+='7450'
    c='9'
    return a+c+b;
}
""")
ctx.call("escramble_758")

是的,你必须像其他人建议的那样用return替换document.write

您还可以使用Js2Py,它是用纯python编写的,能够执行javascript并将其转换为python。几乎支持整个JavaScript,甚至包括标签、getter、setter和其他很少使用的特性。

import js2py

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()
""".replace("document.write", "return ")

result = js2py.eval_js(js)  # executing JavaScript and converting the result to python string 

Js2Py的优点包括可移植性和与python的极易集成(因为基本上JavaScript被翻译成python)。

要安装:

pip install js2py

使用PyV8,我可以做到这一点。但是,我必须用return替换document.write,因为没有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

相关问题 更多 >