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

如何用Python+Selenium获取React页面的NFT组件Prop数据

用Selenium获取React组件的Props数据(Windows + Python)

核心思路

React的内部属性(如__reactProps$xxx)带有随机生成的后缀,无法直接硬编码调用。需要通过JavaScript动态定位组件实例,再提取目标props数据。

实现步骤

1. 初始化Selenium并加载目标页面

确保已安装selenium和对应浏览器驱动(如ChromeDriver),启动浏览器加载目标页面:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# 初始化Chrome浏览器
driver = webdriver.Chrome()
target_url = "https://app.teritori.com/collection/tori-tori1999u8suptza3rtxwk7lspve02m406xe7l622erg3np3aq05gawxsrh9g0p/"
driver.get(target_url)

# 等待目标父组件加载完成
wait = WebDriverWait(driver, 20)
parent_element = wait.until(
    EC.presence_of_element_located((By.CSS_SELECTOR, ".css-1dbjc4n.r-1awozwy.r-13qz1uu"))
)

2. 执行JavaScript提取React Props

通过JS脚本遍历元素的React相关属性,动态定位并提取children.props.data:

# 定义提取props的JS脚本
extract_props_script = """
function getReactProps(element) {
    // 遍历元素属性,匹配React内部实例前缀
    for (const prop in element) {
        if (prop.startsWith('__reactFiber$') || prop.startsWith('__reactInternalInstance$')) {
            const fiber = element[prop];
            let props = fiber.pendingProps || fiber.memoizedProps;
            // 递归查找目标数据结构
            while (props) {
                if (props.children && props.children.props && props.children.props.data) {
                    return props.children.props.data;
                }
                props = props.children ? props.children.props : null;
            }
        }
    }
    return null;
}
return getReactProps(arguments[0]);
"""

# 执行脚本并传入父元素
nft_data = driver.execute_script(extract_props_script, parent_element)

# 处理获取到的NFT数据
if nft_data:
    print("Gorillas NFT列表数据:")
    print(nft_data)
else:
    print("未找到目标数据")

# 关闭浏览器
driver.quit()

关键注意事项

  • 随机后缀兼容:脚本通过匹配__reactFiber$或__reactInternalInstance$前缀,避免硬编码随机后缀,适配不同React版本。
  • 等待渲染完成:必须确保组件完全渲染后再执行脚本,否则会返回null,这里用WebDriverWait实现等待逻辑。
  • React版本适配:不同React版本的内部结构可能有差异,若脚本失效,可尝试调整fiber的属性获取路径(比如fiber.stateNode)。

内容的提问来源于stack exchange,提问作者Juan Antonio Tubío

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 03:50:38