如何使用Selenium执行在网站脚本中定义的JavaScript函数?

2024-10-04 01:22:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我在一个网站上工作,我需要用Selenium运行几个js代码。为了简化操作,我需要运行在网站脚本中声明的函数。
例如,网站使用一个名为document_handler.js的脚本文件,其代码如下:

 (function ($) {
     var getConversationId = function(){
         return $('input[name="conversationId"]').val()
     };
 })(jQuery);

在Selenium中,如果我运行:

^{pr2}$

我得到:

selenium.common.exceptions.WebDriverException: Message: getConversationId is not defined

如果我跑:

js_eval = driver.execute_script("return $.getConversationId()")

我得到:

selenium.common.exceptions.WebDriverException: Message: $.getConversationId is not a function

如何加载网站javascript文件以便在Selenium中使用它的功能?或者我的代码有问题?在


Tags: 文件代码脚本messagereturnis网站selenium
1条回答
网友
1楼 · 发布于 2024-10-04 01:22:13

如果这是您有权访问的脚本,则必须使该函数可用于外部/全局范围。。最简单的方法是将其指定给window对象,它应该可以工作。在

(function ($) {
     window.getConversationId = function(){
         return $('input[name="conversationId"]').val()
     };
 })(jQuery);

或者这样,基本上是一样的。。在

^{pr2}$

相关问题 更多 >