如何通过Selenium获取JavaScript动态生成的Y轴数值?
动态图表Y轴数值获取方案
问题背景
移动光标时图表的X、Y数值会动态变化,X轴数值可通过以下代码正常获取:
driver.find_element(By.CLASS_NAME, "stx-float-date.floatDate").text
但Y轴数值由JavaScript动态更新,尝试多种方法仍无法获取,已尝试的操作包括:
- 调用计算函数:
driver.execute_script("""return z7L""")driver.execute_script("""return window.z7L""")driver.execute_script("return transformedPriceFromPixel()")
- 调用显示相关函数/元素定位:
WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[@class='stx-float-price']"))).get_attribute("innerHTML")driver.execute_script("return q$v.ChartEngine.prototype.updateFloatHRLabel()")
- 读取Local Storage:
driver.execute_script("return window.localStorage;"),未找到目标变量
可行解决方法
1. 检查元素的隐藏属性
部分动态数值会存储在元素的data-*或其他自定义属性中,而非直接显示在innerHTML里:
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By price_element = WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.CLASS_NAME, "stx-float-price"))) # 获取元素所有属性,排查是否有存储数值的字段 all_attributes = driver.execute_script(""" const attrs = {}; for (let i = 0; i < arguments[0].attributes.length; i++) { attrs[arguments[0].attributes[i].name] = arguments[0].attributes[i].value; } return attrs; """, price_element) print(all_attributes) # 直接尝试常见属性 print(price_element.get_attribute("data-price")) print(price_element.get_attribute("value"))
2. 调用图表库的原生API
从类名stx-推测页面可能使用StockCharts库,可尝试直接获取图表实例并读取光标对应的Y值:
y_value = driver.execute_script(""" // 尝试获取图表实例(需根据页面实际挂载方式调整) const chart = window.stxChart || document.querySelector('.stx-chart-container').chart; if (chart && chart.cursor) { return chart.cursor.yValue; // 具体属性名可在浏览器控制台探索确认 } return null; """) print(y_value)
操作前可先在浏览器开发者工具中,移动光标时查看控制台输出或Elements面板的元素更新逻辑,找到准确的API调用方式。
3. 用MutationObserver监听元素变化
通过注入JS监听目标元素的内容变化,实时记录最新数值:
# 注入监听脚本 driver.execute_script(""" const target = document.querySelector('.stx-float-price'); let lastYValue = null; const observer = new MutationObserver((mutations) => { mutations.forEach(mutation => { if (mutation.type === 'childList' || mutation.type === 'characterData') { lastYValue = target.textContent.trim(); } }); }); observer.observe(target, { childList: true, subtree: true, characterData: true }); window.getLatestYValue = () => lastYValue; """) # 移动光标后调用获取数值 y_value = driver.execute_script("return window.getLatestYValue();") print(y_value)
4. 调整元素定位策略
改用presence_of_element_located替代visibility_of_element_located,直接读取元素文本:
y_value = WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.CLASS_NAME, "stx-float-price"))).text print(y_value)
内容的提问来源于stack exchange,提问作者lightspeed192
相关产品推荐
相关产品推荐

