获取硒中 Javascript 代码的返回值

我正在使用Selenium2对我的网站进行一些自动测试,我希望能够获得一些Javascript代码的返回值。如果我的网页中有一个Javascript函数,并且我想调用它并将返回值获取到我的Python代码中,那么我该调用什么来执行此操作?foobar()


答案 1

要返回值,只需在传递给方法的字符串中使用JavaScript关键字,例如returnexecute_script()

>>> from selenium import webdriver
>>> wd = webdriver.Firefox()
>>> wd.get("http://localhost/foo/bar")
>>> wd.execute_script("return 5")
5
>>> wd.execute_script("return true")
True
>>> wd.execute_script("return {foo: 'bar'}")
{u'foo': u'bar'}
>>> wd.execute_script("return foobar()")
u'eli'

答案 2

即使您没有像下面的示例代码那样将代码段编写为函数,也可以返回值,只需在末尾添加 var 是要返回的变量即可。return var;

result = driver.execute_script('''
cells = document.querySelectorAll('a');
URLs = [];
[].forEach.call(cells, function (el) {
    URLs.push(el.href)
});
return URLs
''')

result将包含本例中的数组。URLs