如何使用 selenium 在 python 中执行 Javascript 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14088541/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 10:24:45  来源:igfitidea点击:

How to execute a Javascript function in python with selenium

javascriptpythonseleniumselenium-webdriver

提问by Jose_Sunstrider

I have a function called 'checkdata(code)' in javascript, which, as you can see, takes an argument called 'code' to run and returns a 15-char string.

我在 javascript 中有一个名为“checkdata(code)”的函数,正如您所看到的,它接受一个名为“code”的参数来运行并返回一个 15 个字符的字符串。

So, I found out (and tested) how to call no-argument functions in javascript, but my problem is that when I call checkdata(code), I always get a 'none' return value. This is what I'm doing so far:

所以,我发现(并测试了)如何在 javascript 中调用无参数函数,但我的问题是当我调用 checkdata(code) 时,我总是得到一个“none”返回值。这是我目前正在做的事情:

wd = webdriver.Firefox()
wd.get('My Webpage')
a = wd.execute_script("return checkdata()", code)  //Code is a local variable
                                                   //from my python script
print a

I'm making this, since I read it on an unofficial selenium documentation and here: link

我正在做这个,因为我在非官方 selenium 文档和这里阅读了它:链接

But, as I said before, I just keep getting none printed.

但是,正如我之前所说,我一直没有打印。

How can I call my function passing that parameter?

如何调用传递该参数的函数?

采纳答案by epascarello

Build the string

构建字符串

a = wd.execute_script("return checkdata('" + code + "');")

回答by user839397

Rather than building a string (which means you'd have to escape your quotes properly), try this:

而不是构建一个字符串(这意味着你必须正确地转义你的引号),试试这个:

a = wd.execute_script("return checkdata(arguments[0])", code)