如何使用Python版Selenium在网页中定义JavaScript变量
Hey there! I totally get why this feels confusing—let's break down what's happening and how to fix it.
The Root Cause
When you run driver.execute_script('var apikey = 30'), Selenium executes this code inside an anonymous function context. Variables declared with var (or even let/const without a global scope) are only accessible within that function. Once the function finishes running, the variable gets discarded, which is why your later calls can't find it.
The Fix: Use Global Scope
To make the variable persist across multiple execute_script calls, you need to attach it to the window object (the top-level global scope in browsers). Here's how:
Step 1: Declare the Global Variable
driver.execute_script('window.apikey = 30')
Step 2: Access It Later
Now you can retrieve or use the variable in subsequent script calls:
# Get the variable value apikey_value = driver.execute_script('return window.apikey') print(apikey_value) # Outputs: 30 # Use it in another script driver.execute_script('console.log("API Key:", window.apikey)')
Why This Works
The window object is the top-level global object in browser JavaScript. Any property attached to it is accessible from any script running on the page, including future execute_script calls from Selenium.
A Quick Note on Scope
If you only need the variable within a single execute_script call, your original code would work fine—for example:
driver.execute_script('var apikey = 30; console.log(apikey);') # This logs 30 correctly
The problem only arises when you try to access the variable across separate execute_script invocations.
内容的提问来源于stack exchange,提问作者kenshieva

