如何在Python中用Selenium获取React组件的Props
解决React组件Props获取问题
问题分析
你需要抓取React构建站点中指定组件的Props,已定位到__reactProps$xxx格式的属性名,但通过JS的element[name]或Selenium的get_property均返回None,核心原因如下:
- React内部挂载的这类属性属于不可枚举属性,普通
for...in循环无法遍历到;同时Selenium的get_property仅能访问DOM标准属性,无法直接读取React内部非标准属性。 - 原代码调用
getReactPropComponent时未传入找到的reactElementKey参数,导致函数无法正确定位目标属性。
修正后的代码
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 from pprint import pprint # 整合为单一JS函数,完成从找键到取数据的全流程 js_get_react_data = """ function getReactPropsData(el) { // 获取元素所有属性(含不可枚举属性) const allKeys = Object.getOwnPropertyNames(el); // 匹配ReactProps前缀的属性键 const reactPropKey = allKeys.find(key => key.startsWith('__reactProps$')); if (!reactPropKey) return null; // 逐层获取目标数据 const reactProps = el[reactPropKey]; return reactProps?.children?.props?.data || null; } """ chrome_options = webdriver.ChromeOptions() chrome_options.headless = True # 无头模式添加必要渲染参数 chrome_options.add_argument("--disable-gpu") chrome_options.add_argument("--window-size=1920,1080") chrome_options.add_argument("user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36") driver = webdriver.Chrome(options=chrome_options) driver.get('https://app.teritori.com/collection/tori-tori1999u8suptza3rtxwk7lspve02m406xe7l622erg3np3aq05gawxsrh9g0p/') # 显式等待元素加载完成,替代固定sleep wait = WebDriverWait(driver, 10) element = wait.until(EC.presence_of_element_located( (By.XPATH, "//div[contains(@class, 'r-1sncvnh') and contains(@class, 'r-13qz1uu') and not(contains(@style, 'touch-action'))]") )) # 执行JS获取目标数据 target_data = driver.execute_script(js_get_react_data + "return getReactPropsData(arguments[0]);", element) print("获取到的目标数据:") pprint(target_data) driver.quit()
关键修复点
- 使用
Object.getOwnPropertyNames(el)替代for...in,确保能捕获到React内部的不可枚举属性。 - 将找键、取数据逻辑整合到单个JS函数中,避免参数传递错误。
- 用显式等待替换固定
time.sleep,保证元素完全渲染后再操作,提升稳定性。 - 无头模式添加
user-agent等伪装参数,避免触发站点反爬机制。
额外提示
- React内部属性的后缀(如
__reactProps$42ovhe6scao中的42ovhe6scao)会随打包环境、版本变化,必须通过前缀动态匹配。 - 若目标数据由接口加载,直接抓取对应接口返回的JSON数据会比解析ReactProps更可靠、高效,可通过浏览器开发者工具的"网络"面板定位接口。
内容的提问来源于stack exchange,提问作者Juan Antonio Tubío
相关产品推荐
相关产品推荐

