Ask Your Question
3

Does Selenium have a similar function to Puppeteer's Page.exposeFunction()?

asked 2022-08-15 11:00:00 +0000

djk gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2023-01-10 07:00:00 +0000

ladyg gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-08-15 11:00:00 +0000

Seen: 10 times

Last updated: Jan 10 '23