简体   繁体   中英

Python Selenium JavaScript Executor Variable

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.

You have to set the variable to the window scope instead of the function scope

driver.execute_script("this.test = 'Test Now'")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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