以下是使用Java的WebDriver代码段:
WebDriver driver = new FirefoxDriver(); driver.get("http://www.google.pl/"); driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); WebElement element = driver.findElement(By.name("q")); driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); WebElement query = driver.findElement(By.xpath("//html/body/div[2]/span/center/form/table/tbody/tr/td[2]/div/div/input")); query.sendKeys("asd");
执行代码后,出现以下异常:
线程“主”中的异常org.openqa.selenium.NoSuchElementException:无法找到元素:{“方法”:“ xpath”,“选择器”:” // html / body / div [2] / span / center / form / table / tbody / tr / td [2] / div / div / input“}系统信息:os.name:’Windows 7’,os.arch:’x86’,os.version:‘6.1’,java.version: ‘1.6.0_24’驱动程序信息:driver.version:位于sun.reflect.NativeConstructorAccessorImpl.newInstance0(本地方法)处的sun.reflect.NativeConstructorAccessorImpl.newInstance(本地方法)处的RemoteWebDriver(位于sun.reflect.DelegatingConstructorAccessorImpl.newInstance(未知源)处) org.openqa.selenium.remote处的java.lang.reflect.Constructor.newInstance(未知源)(位于org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:131))。org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:192)上的org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:409)上的ErrorHandler.throwIfResponseFailed(ErrorHandler.java:105) org.openqa.selenium.By $ 6.findElement(By.java:205)的org.openqa.selenium.remote.RemoteWebDriver.findElementByXPath(RemoteWebDriver.java:265)org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:265) java:184)在test.main(test.java:24)在org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:184)处的openqa.selenium.By $ 6.findElement(By.java:205)在test.main(test.java:24)在org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:184)处的openqa.selenium.By $ 6.findElement(By.java:205)在test.main(test.java:24)
我的代码有什么问题?
@ user729076:您为Google文本字段编写的xpath“ // html / body / div [2] / span / center / form / table / tbody / tr / td [2] / div / div / input”不正确。Google文本的HTML字段如下:
<input type="text" value="" autocomplete="off" name="q" class="gbqfif" id="gbqfq" style="border: medium none; padding: 0pt; margin: 0pt; height: auto; width: 100%; background: url("data:image/gif;base64,R0lGODlhAQABAID/AMDAwAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw%3D%3D") repeat scroll 0% 0% transparent; position: absolute; z-index: 6; left: 0px; outline: medium none;" dir="ltr" spellcheck="false">
基于以上HTML,您可以仅使用id或xpath,如下所示:按id:
driver.findElement(By.id("gbqfq")).sendKeys("some text");
通过xpath:
driver.findElement(By.xpath("//input[@id='gbqfq']")).sendKeys("some text");