Как нажать на элемент с помощью Selenium Webdriver - PullRequest
0 голосов
/ 04 июля 2018

Я автоматизирую веб-модуль в браузере Google Chrome с помощью веб-драйвера selenium. Я создал относительный 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 голосов
/ 05 июля 2018

В соответствии с 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();
    
0 голосов
/ 04 июля 2018

Если вы хотите нацелиться на вышеупомянутый Div, вы можете использовать этот Xpath с явным ожиданием.

WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[@ng-click='disableClick || makeEditable()']")));
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...