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

est*_*oza 5 javascript python selenium webdriver

我正在使用Selenium和Python,我正在尝试做两件事:

  • 导入外部javascript文件并执行其中定义的方法
  • 在字符串上定义方法并在评估后调用它们

这是第一种情况的输出:

test.js

function hello(){
  document.body.innerHTML = "testing";
}
Run Code Online (Sandbox Code Playgroud)

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)
Run Code Online (Sandbox Code Playgroud)

对于第二种情况:

>>> 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:
Run Code Online (Sandbox Code Playgroud)

Lou*_*uis 9

如果我创建一个空的html文件并发出问题,我可以让你的第一个案例工作:

f = webdriver.Firefox()
f.get("file://path/to/empty.html")
Run Code Online (Sandbox Code Playgroud)

在此之后,您显示的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()")
Run Code Online (Sandbox Code Playgroud)