获取Selenium中Javascript代码的返回值

问题:获取Selenium中Javascript代码的返回值

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

I’m using Selenium2 for some automated tests of my website, and I’d like to be able to get the return value of some Javascript code. If I have a foobar() Javascript function in my webpage and I want to call that and get the return value into my Python code, what can I call to do that?


回答 0

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

>>> 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'

To return a value, simply use the return JavaScript keyword in the string passed to the execute_script() method, e.g.

>>> 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'

回答 1

即使您没有像下面的示例代码中那样将代码的片段作为函数编写,也可以通过return var;在最后添加var是要返回的变量的方式来返回值。

result = driver.execute_script('''cells = document.querySelectorAll('a');
URLs = []
console.log(cells);
[].forEach.call(cells, function (el) {
    if(el.text.indexOf("download") !== -1){
    //el.click();
    console.log(el.href)
    //window.open(el.href, '_blank');
    URLs.push(el.href)
    }
});
return URLs''')

result将包含在URLs这种情况下的数组。

You can return values even if you don’t have your snipped of code written as a function like in the below example code, by just adding return var; at the end where var is the variable you want to return.

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

result will contain the array that is in URLs this case.