简体   繁体   English

使用 Selenium 添加 JavaScript 事件监听器会自动触发它

[英]Adding JavaScript event listener with Selenium triggers it automatically

As there is (according to my research) no way to catch user input with selenium, I am trying to use a JavaScript event listener.由于(根据我的研究)无法使用 selenium 捕获用户输入,因此我正在尝试使用 JavaScript 事件侦听器。

But when I add the event listener by executing the JavaScript code, the function is automatically triggered without me (as the user) doing anything.但是,当我通过执行 JavaScript 代码添加事件侦听器时,function 会自动触发,而我(作为用户)没有做任何事情。 Furthermore, there is no way to trigger the function again.此外,无法再次触发 function。

Does anyone know what the problem might be and how I could solve it?有谁知道问题可能是什么以及我该如何解决? FYI: My code is in Python 3.8仅供参考:我的代码在 Python 3.8

Thank you in advance, Raphael提前谢谢你,拉斐尔

# this is a self defined function that creates a new selenium WebDriver
browser = gf.create_browser(headless=False)

browser.get("https://www.google.com")

browser.execute_script('document.getElementById("hplogo").addEventListener("mouseover",console.log("Success"))')

time.sleep(90)

The console displays "success" as soon as the script is executed, afterwards the event is never triggered again.脚本一执行,控制台就会显示“成功”,之后该事件将不再触发。 I have tried different events (click, mouseover,...), different functions and different websites with different elemtents.我尝试过不同的事件(点击、鼠标悬停、...)、不同的功能和不同的网站具有不同的元素。

You're not passing a function – you're actually just directly calling it你没有通过 function - 你实际上只是直接调用

console.log("Success")

This ^ calls the function.这个 ^ 调用 function。 The actually parameter you end up passing is the result of console.log , not the function itself (which if I remember is just an undefined ).您最终传递的实际参数是console.log的结果,而不是 function 本身(如果我记得只是undefined )。 If you want to actually pass a function, you should make something like this.如果你想实际传递一个 function,你应该做这样的事情。

() => console.log("Success")

For pre ES6 supported browsers, you can use:对于 ES6 之前支持的浏览器,您可以使用:

function(){console.log("Success")}

The code is entirely a infinite loop because of which it is triggering only once and then after it is not triggering.该代码完全是一个无限循环,因为它只触发一次,然后在它不触发之后。 It is suggested to edit your code as建议将您的代码编辑为

addEventListener("mouseover",{console.log("Success")})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM