如何在div类下找到文本

时间:2013-04-16 10:39:55

标签: java selenium webdriver

我正在使用Internet Explorer作为浏览器来自动化测试,使用webdriver。我的问题是,如何在div类下找到文本?

我的HTML看起来像这样:

<div class="welcome_text">
Text-Welcome Vijayanand

我试过像这样使用XPath

WebElement webelement=driver.findElement(By.xpath("//div[@Class='welcome_text']/div"));
webelement.getText();

但是我收到如下错误:

Exception in thread "main" org.openqa.selenium.NoSuchElementException: Unable to find element with xpath == //DIV[@Class='welcome_text']/DIV (WARNING: The server did not provide any stacktrace information)

Command duration or timeout: 656 milliseconds

For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html

Build info: version: '2.32.0', revision: '6c40c18', time: '2013-04-09 17:23:22'

System info: os.name: 'Windows XP', os.arch: 'x86', os.version: '5.1', java.version: '1.6.0_05'

Session ID: 87815f2f-f6ff-4689-ac34-befb114acfe4

Driver info: org.openqa.selenium.ie.InternetExplorerDriver

Capabilities [{platform=WINDOWS, elementScrollBehavior=0, javascriptEnabled=true, enablePersistentHover=true, ignoreZoomSetting=false, browserName=internet explorer, enableElementCacheCleanup=true, unexpectedAlertBehaviour=dismiss, version=8, cssSelectorsEnabled=true, ignoreProtectedModeSettings=true, requireWindowFocus=false, allowAsynchronousJavaScript=true, handlesAlerts=true, initialBrowserUrl=, nativeEvents=true, takesScreenshot=true}]

      at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)

      at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)

      at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)

      at java.lang.reflect.Constructor.newInstance(Unknown Source)

      at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:187)

      at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:145)

      at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:554)

      at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:307)

      at org.openqa.selenium.remote.RemoteWebDriver.findElementByXPath(RemoteWebDriver.java:404)

      at org.openqa.selenium.By$ByXPath.findElement(By.java:344)

      at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:299)

      at internetexplorerlaunch.IElaunch.main(IElaunch.java:44)

2 个答案:

答案 0 :(得分:1)

尝试By.className()方法,如下所示。

WebElement webelement=driver.findElement(By.className("welcome_text"));

webelement.getText();

答案 1 :(得分:1)

你的XPATH错了:

WebElement webelement=driver.findElement(By.xpath("//div[@Class='welcome_text']/div"));
webelement.getText(); 

应该是:

driver.findElement(By.xpath("//div[@class='welcome_text']"));