1 | initial version |
Yes, Selenium does have a similar function called execute_script()
. It allows you to execute JavaScript on the browser and pass data between Python and the browser. Here's an example:
from selenium import webdriver
driver = webdriver.Chrome()
driver.get("https://www.google.com")
# Define a function that will be exposed to the browser
def my_python_function(param):
print("Received parameter:", param)
# Expose the function to the browser using execute_script()
driver.execute_script("window.myBrowserFunction = function(param) { return pywebex_bridge(param); }", my_python_function)
# Call the function from the browser using JavaScript
driver.execute_script("window.myBrowserFunction('hello')")
In this example, we define a Python function my_python_function
that receives a parameter and prints it. We then expose this function to the browser by creating a JavaScript function on the browser called myBrowserFunction
. This JavaScript function calls pywebex_bridge
, which is the communication channel between Python and the browser. We pass my_python_function
as a parameter to pywebex_bridge
so that it can be called from the browser.
We then call myBrowserFunction
from the browser using execute_script()
. The parameter 'hello'
is passed to myBrowserFunction
, which calls pywebex_bridge
and passes the parameter to my_python_function
. The result is that 'Received parameter: hello'
is printed to the Python console.