'Selenium: How to execute scripts within the browser?
My current goal is to execute a script to my selenium browser that declares a var and then using DevTools access the variable in console log.
Here is the conflicting script:
from selenium import webdriver
from time import sleep
chromePath = 'Selenium Injection\chromedriver.exe'
driver = webdriver.Chrome(executable_path=chromePath)
driver.get('https://www.google.com')
driver.execute_script(
"var test = 'Test Now';"
"return test"
)
Upon execution I try to access the test variable and I get an error.
Solution 1:[1]
You have to set the variable to the window scope instead of the function scope
driver.execute_script("this.test = 'Test Now'")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | BrunoT |