HTML结构变化时,如何通过固定文本获取strong标签内文本值
跨HTML结构变化获取关联的strong标签文本
问题背景
任务执行前后页面HTML结构发生变化:
- 执行前结构:
<div> <strong>heizil</strong>: <label id="check_label"> <em class="Highlight" style="padding: 1px; box-shadow: rgb(229, 229, 229) 1px 1px; border-radius: 3px; background-color: rgb(0, 191, 255); color: rgb(0, 0, 0); font-style: inherit;" match="test" loopnumber="385144110">Test</em> device testing - Android testing </label> </div>
- 执行后结构:
<a id="id_1008326" class="activity"> <strong>heizil</strong> : <label id="check_label"> "device testing - Android testing" </label> </a>
现有代码仅能在任务执行后成功获取结果,执行前会抛出元素不存在异常:
System.out.println(driver.findElement(By.xpath("//a[@class='activity'][contains(.,'Android testing')]/strong")).getText());
需求:借助唯一固定文本device testing - Android testing,实现无论任务执行前后,都能获取<strong>标签内的heizil文本。
解决方案
可以通过两种通用XPath策略实现跨结构匹配:
方案1:通过label的固定文本定位其兄弟strong节点
利用label标签包含目标固定文本的特性,定位到该label后,获取它的前兄弟节点<strong>:
// 匹配包含目标文本的label,取其前一个兄弟strong元素 String xpath = "//label[contains(., 'device testing - Android testing')]/preceding-sibling::strong[1]"; System.out.println(driver.findElement(By.xpath(xpath)).getText());
注:使用contains(., ...)而非contains(text(), ...),是因为前者会匹配当前节点及其所有子节点的文本内容,兼容执行前label内包含<em>子标签的场景。
方案2:定位包含固定文本的父容器,再找内部的strong
不管父容器是<div>还是<a>,只要它包含目标固定文本,就定位该容器,再在内部查找<strong>元素:
// 匹配包含目标文本的任意父容器,取其中的第一个strong元素 String xpath = "//*[contains(., 'device testing - Android testing')]//strong[1]"; System.out.println(driver.findElement(By.xpath(xpath)).getText());
该方案兼容性更强,只要目标<strong>和固定文本处于同一父容器内,无论父容器标签类型如何变化,都能匹配到目标元素。
额外优化建议
为避免页面加载延迟导致的元素定位失败,建议结合显式等待:
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10)); WebElement strongElement = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[contains(., 'device testing - Android testing')]//strong[1]"))); System.out.println(strongElement.getText());
内容的提问来源于stack exchange,提问作者nayansFosgit
相关产品推荐
相关产品推荐

