You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python版Selenium在网页中定义JavaScript变量

How to Properly Define JavaScript Variables in a Web Page Using Selenium

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 00:27:41