如何使用Selenium Webdriver单击元素

时间:2018-07-04 08:38:57

标签: java selenium selenium-webdriver xpath css-selectors

我正在通过使用Selenium Web驱动程序在google chrome浏览器中自动化Web模块。我已经创建了一个Web元素的相对XPath,但我想单击它,但不幸的是,它无法正常工作,并且给我一个例外,该XPath不在网页上。动态XPath不能正常工作,因为我首先捕获了这一点,这就是为什么我创建了相对XPath。

硒代码:

//Dashboard:
WebElement ele = driver.findElement(By.xpath("//*[@id=\"sidebar\"]/section/ul/li[1]/a"));
Actions action = new Actions(driver);
action.moveToElement(ele).perform(); // Mover Hover     
WebElement ele2 = driver.findElement(By.xpath("//*[@id=\"sidebar\"]/section/ul/li[1]/ul/li[1]/a"));
ele2.click(); // Click onto Weather
driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);
WebElement ele4 = driver.findElement(By.xpath("//*[contains(@id, 'pvExplorationHost')]//li[1]/div"));
ele4.click();

网页上的HTML代码:

<div class="textLabel" ng-click="disableClick || makeEditable()" title="Waffle Charts - All Variables">Waffle Charts - All Variables</div>

[在此处输入图片描述] [1]

硒发生异常

Only local connections are allowed.
Jul 04, 2018 2:15:14 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: OSS
Test Passed!
Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//*[contains(@id, 'pvExplorationHost')]//li[1]/div"}
  (Session info: chrome=67.0.3396.99)
  (Driver info: chromedriver=2.38.552522 (437e6fbedfa8762dec75e2c5b3ddb86763dc9dcb),platform=Windows NT 6.1.7601 SP1 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 0 milliseconds
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '3.12.0', revision: '7c6e0b3', time: '2018-05-08T15:15:03.216Z'
System info: host: 'MACPK-WKS-0072', ip: '192.168.8.100', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '10'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities {acceptInsecureCerts: false, acceptSslCerts: false, applicationCacheEnabled: false, browserConnectionEnabled: false, browserName: chrome, chrome: {chromedriverVersion: 2.38.552522 (437e6fbedfa876..., userDataDir: C:\Users\MOMNA~1.ARS\AppDat...}, cssSelectorsEnabled: true, databaseEnabled: false, handlesAlerts: true, hasTouchScreen: false, javascriptEnabled: true, locationContextEnabled: true, mobileEmulationEnabled: false, nativeEvents: true, networkConnectionEnabled: false, pageLoadStrategy: normal, platform: XP, platformName: XP, rotatable: false, setWindowRect: true, takesHeapSnapshot: true, takesScreenshot: true, unexpectedAlertBehaviour: , unhandledPromptBehavior: , version: 67.0.3396.99, webStorageEnabled: true}
Session ID: 2615a71e0f1b2d97c0611fc399cdda8b
*** Element info: {Using=xpath, value=//*[contains(@id, 'pvExplorationHost')]//li[1]/div}
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.base/java.lang.reflect.Constructor.newInstance(Unknown Source)
    at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:214)
    at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:166)
    at org.openqa.selenium.remote.http.JsonHttpResponseCodec.reconstructValue(JsonHttpResponseCodec.java:40)
    at org.openqa.selenium.remote.http.AbstractHttpResponseCodec.decode(AbstractHttpResponseCodec.java:80)
    at org.openqa.selenium.remote.http.AbstractHttpResponseCodec.decode(AbstractHttpResponseCodec.java:44)
    at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:158)
    at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:83)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:543)
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:317)
    at org.openqa.selenium.remote.RemoteWebDriver.findElementByXPath(RemoteWebDriver.java:419)
    at org.openqa.selenium.By$ByXPath.findElement(By.java:353)
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:309)
    at newpackage.DynamicXPath.main(DynamicXPath.java:74)

请告知我,我对Selenium Web-Driver陌生。

2 个答案:

答案 0 :(得分:0)

如果要定位上述Div,则可以将此Xpath与Explicit wait一起使用。

WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[@ng-click='disableClick || makeEditable()']")));

答案 1 :(得分:0)

根据 HTML ,您共享了所需的元素为Angular元素,因此必须诱使 WebDriverWait 使元素可点击,您可以使用以下任一解决方案:

  • cssSelector

    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("div.textLabel[title='Waffle Charts - All Variables']"))).click();
    
  • xpath

    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//div[@class='textLabel' and @title='Waffle Charts - All Variables'][contains(.,'Waffle Charts - All Variables')]"))).click();