Selenium Webdriver: execute_script无法执行自定义方法和外部javascript文件

5 投票
2 回答
12432 浏览
提问于 2025-04-18 03:48

我正在使用Selenium和Python,想要做两件事情:

  • 导入一个外部的JavaScript文件,并执行里面定义的方法
  • 在一个字符串上定义方法,并在评估后调用它们

这是第一个情况的输出:

test.js

function hello(){
  document.body.innerHTML = "testing";
}

Python代码

>>> from selenium import webdriver
>>> f = webdriver.Firefox()
>>> f.execute_script("var s=document.createElement('script');\
...                                s.src='file://C:/test.js';\
...                                s.type = 'text/javascript';\
...                                document.head.appendChild(s)")
>>> f.execute_script("hello")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python27\lib\site-packages\selenium-2.41.0-py2.7.egg\selenium\webdriver\remote\webdriver.py", line 394, in execute_script
{'script': script, 'args':converted_args})['value']
  File "C:\Python27\lib\site-packages\selenium-2.41.0-py2.7.egg\selenium\webdriver\remote\webdriver.py", line 166, in execute
self.error_handler.check_response(response)
  File "C:\Python27\lib\site-packages\selenium-2.41.0-py2.7.egg\selenium\webdriver\remote\errorhandler.py", line 164, in check_response
raise exception_class(message, screen, stacktrace) selenium.common.exceptions.WebDriverException: Message: u'hello is not defined' ; Stacktrace:
  at anonymous (about:blank:68)
  at handleEvaluateEvent (about:blank:68)

对于第二个情况:

>>> js = "function blah(){document.body.innerHTML='testing';}"
>>> f.execute_script(js)
>>> f.execute_script("blah")
    ...
    raise exception_class(message, screen, stacktrace) selenium.common.exceptions.WebDriverException: Message: u'blah is not defined' ; Stacktrace:

相关问题:

2 个回答

1

这段代码是用来处理一些特定的功能的。它可能涉及到一些编程的基本概念,比如变量、循环或者条件判断等。具体来说,代码块中的内容会根据不同的输入或条件来执行不同的操作。

如果你是编程新手,可以把这段代码想象成一个简单的指令列表,计算机会按照这些指令一步一步地执行。每一行代码就像是给计算机下达的一个命令,告诉它该做什么。

总之,这段代码的目的是为了实现某种功能,具体的实现方式可能会涉及到一些编程的基本知识,但只要理解了每一行的意思,就能明白它的整体作用。

driver.execute_script("window.a = function(a,b) {return a + b;}")


print driver.execute_script("return a(1,2)")
10

我可以让你的第一个例子正常工作,只需要创建一个空的html文件,然后执行:

f = webdriver.Firefox()
f.get("file://path/to/empty.html")

这样一来,你提供的JavaScript代码就可以顺利运行了。不过,当我在Firefox中尝试你提到的代码时,没有出现错误,但在Chrome中却提示:“不允许加载本地资源”。我认为问题出在跨域请求上。

至于你的第二个例子,问题在于Selenium在后台把你的JavaScript代码包裹在一个匿名函数里。所以你的blah函数只在这个匿名函数内部可用。如果你想让它变成全局可用,就得把它赋值给window,像这样:

>>> from selenium import webdriver
>>> f = webdriver.Firefox()
>>> f.execute_script("window.blah = function () {document.body.innerHTML='testing';}")
>>> f.execute_script("blah()")

撰写回答