【发布时间】:2014-03-20 00:37:07
【问题描述】:
<div id="pdiv">
<table width="100%" cellspacing="0" cellpadding="0" border="0" align="left">
<tbody>
<tr>
<td class="normtxt" width="100%" colspan="2">Please answer this simple math question</td>
</tr>
<tr>
<td width="18%" align="left" style="padding:0">
<span id="mathq2" style="padding-bottom: 5px;">6 + 4 = </span>
</td>
<td align="left">
<span id="mathans2" style="display: none;">8</span>
<input id="mathuserans2" type="text" name="mathuserans2" value="" style="width: 100px;">
</td>
<input type="hidden" value="32317377" name="txtPolliD">
</tr>
</tbody>
</table>
我正在尝试使用 webdriver 从上述 html 代码中获取动态跨度文本,但得到:
org.openqa.selenium.NoSuchElementException: 无法定位元素:{"method":"id","selector":"mathq2"}
我需要从 span id 'mathq2' 中获取文本:'6 + 4 ='
每次刷新页面或加载新页面时,此文本“6 + 4 =”都会发生变化
我尝试过 xpath、id、cssselector,但总是遇到无法定位元素:{"method":"id","selector":"mathq2"}
这是我的代码:
private static WebDriverWait wait = new WebDriverWait(wd,90);
try{
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("mathq2")));
}catch(org.openqa.selenium.TimeoutException e){
System.out.println("wait time outexception: " + e);
}
wd.findElement(By.xpath(".//*[@id='mathq2']")).click();
mathTxt = wd.findElement(By.xpath(".//*[@id='mathq2']")).getText();
//wd.findElement(By.id("mathq2")).click();
//mathTxt = wd.findElement(By.id("mathq2")).getText();
//mathTxt = wd.findElement(By.cssSelector("#pdiv span.mathq2")).getText();
//mathTxt = (String)((JavascriptExecutor)wd).executeScript(" {document.getElementById('mathq2').innerHTML;}");
我也试过 javascriptexecutor 当尝试 javascriptexecutor 我得到:org.openqa.selenium.WebDriverException: document.getElementById(...) is null
顺便说一句,Selenium IDE 使用 xpath 查找元素并存储文本。我将 Selenium IDE 测试用例导出到 Java/Junit4/Webdriver,然后在 eclipse 中运行它并得到相同的 NoSuchElementException。
请帮忙。谢谢
【问题讨论】:
-
id呢,是动态的吗?
-
请分享网页的网址或呈现的完整HTML代码
-
感谢您的回复。我不相信跨度 ID 是动态的。它始终是 span id="mathq2"。但是当您刷新页面或打开新页面时,文本“6 + 4 =”是动态的。网址是:timesofindia.in
-
在 Firefox、Chrome、IE 和 Safari 浏览器中尝试过,结果相同:NoSuchElementException: Unable to locate element