无法定位Google Chart工具提示元素 - Protractor & TypeScript求助
解决Protractor+TypeScript中Google Chart工具提示元素定位问题
刚上手Protractor和TypeScript遇到这种动态元素定位问题太正常了,Google Chart的工具提示属于动态生成元素,必须先触发显示动作,还要处理加载延迟,这也是你之前的XPath没生效的核心原因。结合你给出的DOM结构,我给你整理几个可行的解决方案:
关键前提:先触发工具提示显示
工具提示只有在鼠标悬停到对应日期上才会出现,所以第一步必须模拟hover动作(这里需要你根据实际DOM调整日期元素的定位器,比如假设日期在chart的某个td里):
// 定位今日日期元素(请根据实际页面DOM修改这个定位器) const todayDateElement = element(by.css('google-chart td.date-today')); // 模拟鼠标悬停,触发工具提示显示 await browser.actions().mouseMove(todayDateElement).perform();
方案一:优化XPath+等待元素可见
你的原XPath大概率因为元素还没渲染完成就查找导致失败,加上等待条件会大幅提升稳定性:
import { Target, by, browser, ExpectedConditions as EC } from 'protractor'; // 先等待工具提示容器加载完成并可见 const tooltipContainer = element(by.xpath("//summary-report//div[contains(@aria-label, 'test sample')]")); await browser.wait(EC.visibilityOf(tooltipContainer), 5000, '工具提示未在5秒内显示'); // 定位三个数值元素 static testValue1 = Target.the("第一个数值123").located(by.xpath("//summary-report//div[contains(@aria-label, 'test sample')]/table/tbody/tr[4]/td[1]")); static testValue2 = Target.the("第二个数值231").located(by.xpath("//summary-report//div[contains(@aria-label, 'test sample')]/table/tbody/tr[4]/td[2]")); static testValue3 = Target.the("第三个数值10").located(by.xpath("//summary-report//div[contains(@aria-label, 'test sample')]/table/tbody/tr[4]/td[3]"));
方案二:用CSS选择器简化定位
如果DOM层级稳定,CSS选择器会比XPath更简洁易读:
// 先等待工具提示内的表格可见 await browser.wait(EC.visibilityOf(element(by.css('summary-report div[aria-label*="test sample"] table'))), 5000); // 定位三个td元素 static testValue1 = Target.the("第一个数值123").located(by.css('summary-report div[aria-label*="test sample"] table tbody tr:nth-child(4) td:nth-child(1)')); static testValue2 = Target.the("第二个数值231").located(by.css('summary-report div[aria-label*="test sample"] table tbody tr:nth-child(4) td:nth-child(2)')); static testValue3 = Target.the("第三个数值10").located(by.css('summary-report div[aria-label*="test sample"] table tbody tr:nth-child(4) td:nth-child(3)'));
方案三:按文本内容定位(如果数值固定)
如果这三个数值是固定不变的,也可以直接通过文本精准定位:
static testValue1 = Target.the("第一个数值123").located(by.xpath("//summary-report//td[text()='123']")); static testValue2 = Target.the("第二个数值231").located(by.xpath("//summary-report//td[text()='231']")); static testValue3 = Target.the("第三个数值10").located(by.xpath("//summary-report//td[text()='10']"));
额外注意事项
- 如果是Angular项目,记得确保Protractor等待Angular稳定:
await browser.waitForAngularEnabled(true); - 少数情况下Google Chart的工具提示会被生成在
body根节点下,不是嵌套在google-chart里,这时需要把定位器的根节点改成//body//div[contains(@aria-label, 'test sample')]
内容的提问来源于stack exchange,提问作者Upa A
相关产品推荐
相关产品推荐

