繁体   English   中英

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

[英]Selenium Webdriver: execute_script can't execute custom methods and external javascript files

我正在使用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:

如果我创建一个空的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()")
driver.execute_script("window.a = function(a,b) {return a + b;}")


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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM