我正在使用Selenium和Python,我正在尝试做两件事:
这是第一种情况的输出:
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:
答案 0 :(得分:9)
如果我创建一个空的html文件并发出问题,我可以让你的第一个案例工作:
f = webdriver.Firefox()
f.get("file://path/to/empty.html")
在此之后,您显示的JavaScript将毫无问题地执行。当我尝试您在问题中显示的代码时,Firefox不会给我一个错误,但Chrome会说:&#34;不允许加载本地资源&#34;。我认为问题是跨域请求。
第二种情况的问题是幕后的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()")
答案 1 :(得分:1)
driver.execute_script("window.a = function(a,b) {return a + b;}")
print driver.execute_script("return a(1,2)")