#java #selenium #xpath #dropdown
#java #selenium #xpath #выпадающий
Вопрос:
Я использовал все виды локаторов, чтобы найти веб-элемент выпадающего списка, но он не работает каждый раз, когда я получаю эту ошибку:
Не удается найти элемент
Я пытаюсь по указанному URL войти в систему и выбрать календарь здесь: https://classic.crmpro.com /
Я использовал следующие способы определения местоположения после использования неявного ожидания:
driver.manage().timeouts().implicitlyWait(500, TimeUnit.SECONDS);
-
driver.findElement(By.xpath(«//a[@href=’https://classic.crmpro.com/system/index.cfm?action=calendaramp;sub=default ‘]»)).нажмите();
-
driver.findElement(By.xpath(«//*[@id=’navmenu’]/ul /li[2] /a»)).click();
-
driver.findElement(By.xpath(«//*[@title=’Calendar’]»)).click();
-
driver.findElement(By.xpath(«//*[содержит(текст(),’Календарь’)]»)).click();
-
driver.findElement(By.xpath(«//*[@title=’Calendar’]»)).click(); Thread.sleep(1000);
Каждый раз, когда он выдает ошибку типа:
Starting ChromeDriver 2.46.628402 (536cd7adbad73a3783fdc2cab92ab2ba7ec361e1) on port 12336
Only local connections are allowed.
Please protect ports used by ChromeDriver and related test frameworks to prevent access by malicious code.
Mar 31, 2019 3:45:38 AM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: OSS
Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@title='Calendar']"}
(Session info: chrome=73.0.3683.86)
(Driver info: chromedriver=2.46.628402 (536cd7adbad73a3783fdc2cab92ab2ba7ec361e1),platform=Windows NT 6.3.9600 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 0 milliseconds
For documentation on this error, please visit: https://www.seleniumhq.org/exceptions/no_such_element.html
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:17:03'
System info: host: 'YESHI', ip: '192.168.0.103', os.name: 'Windows 8.1', os.arch: 'amd64', os.version: '6.3', java.version: '1.8.0_121'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities {acceptInsecureCerts: false, acceptSslCerts: false, applicationCacheEnabled: false, browserConnectionEnabled: false, browserName: chrome, chrome: {chromedriverVersion: 2.46.628402 (536cd7adbad73a..., userDataDir: C:UsersHPAppDataLocalT...}, cssSelectorsEnabled: true, databaseEnabled: false, goog:chromeOptions: {debuggerAddress: localhost:50027}, handlesAlerts: true, hasTouchScreen: false, javascriptEnabled: true, locationContextEnabled: true, mobileEmulationEnabled: false, nativeEvents: true, networkConnectionEnabled: false, pageLoadStrategy: normal, platform: XP, platformName: XP, proxy: Proxy(), rotatable: false, setWindowRect: true, strictFileInteractability: false, takesHeapSnapshot: true, takesScreenshot: true, timeouts: {implicit: 0, pageLoad: 300000, script: 30000}, unexpectedAlertBehaviour: ignore, unhandledPromptBehavior: ignore, version: 73.0.3683.86, webStorageEnabled: true}
Session ID: 5e04eddb3f57b98161681cab972a5b2a
*** Element info: {Using=xpath, value=//*[@title='Calendar']}
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
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:552)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:323)
at org.openqa.selenium.remote.RemoteWebDriver.findElementByXPath(RemoteWebDriver.java:428)
at org.openqa.selenium.By$ByXPath.findElement(By.java:353)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:315)
at YeshiProject.demo.main(demo.java:34)
Пожалуйста, дайте мне знать, что я могу сделать.
Комментарии:
1. Добро пожаловать в SO. Не могли бы вы, пожалуйста, предоставить HTML всего navmenu. Я не могу получить доступ к странице, которую вы упомянули, поскольку для этого нужны учетные данные пользователя.
2. У вас есть фиктивный набор учетных данных, которые будут использоваться участниками?
Ответ №1:
Ваша проблема решена? Если нет, пожалуйста, сделайте это.
Элемент, который вы имели в виду, находится внутри iframe
, поэтому вам сначала нужно переключиться.
Это iframe
я имею в виду : By.name("mainpanel")
После входа в систему вы можете сделать это:
new WebDriverWait(driver, 20).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.name("mainpanel")));
driver.findElement(By.xpath("//*[@title='Calendar']")).click();
Он нажмет на calendar
, но если вы просто хотите перейти к элементу и отобразить выпадающий список, то сделайте это:
new WebDriverWait(driver, 20).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.name("mainpanel")));
Actions act = new Actions(driver);
act.moveToElement(driver.findElement(By.xpath("//*[@title='Calendar']"))).perform();
Следующий импорт:
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.interactions.Actions;
Извините за учетные данные, я предлагаю изменить ваши учетные данные и удалить их с этого сайта.
Надеюсь, это поможет.
Комментарии:
1. Спасибо за ваш ответ и удалил бы creds