InvalidArgumentException: недопустимый аргумент и InvalidSelectorException: недопустимая ошибка селектора с ChromeDriver и Chrome с использованием Selenium с Java - PullRequest
1 голос
/ 20 января 2020

Я никогда раньше не сталкивался с такой ошибкой. Является ли посещаемый мной веб-сайт устойчивым к использованию тестов автоматизации?

Код:

public class DirectoryAutomation {

    public static void main(String[] args) throws IOException, InterruptedException {

        System.setProperty("webdriver.chrome.driver", "C:\\Users\\MartinErlic\\eclipse-workspace\\DirectoryAutomation\\libs\\chromedriver.exe");
        ChromeDriver driver = new ChromeDriver();
        driver.get("https://www.arivify.com/property/az/mesa");
        Thread.sleep(2000);
        driver.findElement(By.xpath("xpath=//div[@id='__layout']/div/div[2]/section/div/table/tbody/tr/td")).click();
    }
}

Исключение:

Starting ChromeDriver 78.0.3904.105 (60e2d8774a8151efa6a00b1f358371b1e0e07ee2-refs/branch-heads/3904@{#877}) on port 21763
Only local connections are allowed.
Please protect ports used by ChromeDriver and related test frameworks to prevent access by malicious code.
[1579544613.399][WARNING]: This version of ChromeDriver has not been tested with Chrome version 79.
[1579544615.411][WARNING]: Timed out connecting to Chrome, retrying...
Jan. 20, 2020 10:23:37 A.M. org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: W3C
Exception in thread "main" org.openqa.selenium.InvalidArgumentException: invalid argument
  (Session info: chrome=79.0.3945.130)
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:17:03'
System info: host: 'DESKTOP-AS2OG7F', ip: '217.157.87.231', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '13.0.1'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities {acceptInsecureCerts: false, browserName: chrome, browserVersion: 79.0.3945.130, chrome: {chromedriverVersion: 78.0.3904.105 (60e2d8774a81..., userDataDir: C:\Users\MARTIN~1\AppData\L...}, goog:chromeOptions: {debuggerAddress: localhost:60322}, javascriptEnabled: true, networkConnectionEnabled: false, pageLoadStrategy: normal, platform: XP, platformName: XP, proxy: Proxy(), setWindowRect: true, strictFileInteractability: false, timeouts: {implicit: 0, pageLoad: 300000, script: 30000}, unhandledPromptBehavior: dismiss and notify}
Session ID: 613ee3b0588734b777f2ceb5d7715c9c
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:500)
    at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:481)
    at org.openqa.selenium.remote.http.W3CHttpResponseCodec.createException(W3CHttpResponseCodec.java:187)
    at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:122)
    at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:49)
    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.get(RemoteWebDriver.java:277)
    at DirectoryAutomation.main(DirectoryAutomation.java:42)

Обновлено исключение:

Starting ChromeDriver 79.0.3945.36 (3582db32b33893869b8c1339e8f4d9ed1816f143-refs/branch-heads/3945@{#614}) on port 24206
Only local connections are allowed.
Please protect ports used by ChromeDriver and related test frameworks to prevent access by malicious code.
[1579548408.283][WARNING]: Timed out connecting to Chrome, retrying...
Jan. 20, 2020 11:26:50 A.M. org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: W3C
Exception in thread "main" org.openqa.selenium.InvalidSelectorException: invalid selector: Unable to locate an element with the xpath expression xpath=//a[contains(@href,'/property/search/hEC4ocSW0')] because of the following error:
TypeError: Failed to execute 'evaluate' on 'Document': The result is not a node set, and therefore cannot be converted to the desired type.
  (Session info: chrome=79.0.3945.130)
For documentation on this error, please visit: https://www.seleniumhq.org/exceptions/invalid_selector_exception.html
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:17:03'
System info: host: 'DESKTOP-AS2OG7F', ip: '192.168.1.75', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '13.0.1'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities {acceptInsecureCerts: false, browserName: chrome, browserVersion: 79.0.3945.130, chrome: {chromedriverVersion: 79.0.3945.36 (3582db32b3389..., userDataDir: C:\Users\MARTIN~1\AppData\L...}, goog:chromeOptions: {debuggerAddress: localhost:51045}, javascriptEnabled: true, networkConnectionEnabled: false, pageLoadStrategy: normal, platform: WINDOWS, platformName: WINDOWS, proxy: Proxy(), setWindowRect: true, strictFileInteractability: false, timeouts: {implicit: 0, pageLoad: 300000, script: 30000}, unhandledPromptBehavior: dismiss and notify}
Session ID: c52709d658575c36b6705f1db4ce20b2
*** Element info: {Using=xpath, value=xpath=//a[contains(@href,'/property/search/hEC4ocSW0')]}
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:500)
    at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:481)
    at org.openqa.selenium.remote.http.W3CHttpResponseCodec.createException(W3CHttpResponseCodec.java:187)
    at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:122)
    at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:49)
    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 DirectoryAutomation.main(DirectoryAutomation.java:42)

Ответы [ 2 ]

2 голосов
/ 20 января 2020

Происходит ли это, если вы пробуете другие веб-сайты, использующие этот же код (в частности, с той же версией веб-драйвера и chrome версия)?

Просмотр этого [1579544613.399][WARNING]: This version of ChromeDriver has not been tested with Chrome version 79.. Сообщает, что вы, вероятно, используете несовместимые версии вашего драйвера.exe и chrome.

Видя, что вы используете chrome версию 79, вы должны получить версию хроматографа, соответствующую ей https://chromedriver.chromium.org/downloads, что составляет 79.0.3945.36. Вы используете 78.0.3904.105 в настоящее время.

Несмотря на то, что метод get(url) происходит, что может создать впечатление, что веб-сайт вносит свой вклад в эту ошибку, я считаю, что это случайно, и проблема возникнет при первой инструкции к браузер, независимо от того, какой это тип.

Редактировать. Это выглядит как новая проблема. Убедитесь, что ваш xpath указывает на допустимый элемент и страница полностью загружается. Для тестирования я предлагаю попытаться найти более простой xpath в постоянной части страницы рядом с элементом root, чтобы убедиться, что поиск работает в целом. Это исключение говорит о том, что вы все настроены и вам нужно начать настройку на сайт, чтобы получить время и поиск работы

0 голосов
/ 20 января 2020

Первое предупреждение ...

[WARNING]: This version of ChromeDriver has not been tested with Chrome version 79

... было связано с несовместимостью между версиями двоичных файлов, когда вы пытались инициировать / порождать новую Контекст просмотра т.е. Chrome Браузер сеанс:

  • хром = 79.0.3945.130 до
  • chromedriverVersion: 78.0.3904.105

Кажется, вы решили эту проблему, обновив Chrome и ChromeDriver до идентичных уровней.

Подробное обсуждение можно найти в . Эта версия ChromeDriver не была протестирована с Chrome Ошибка версии 79 при выполнении испытаний ProtractorE2E с ChromeDriver Chrome Селен


Второе сообщение об ошибке ...

Exception in thread "main" org.openqa.selenium.InvalidSelectorException: invalid selector: Unable to locate an element with the xpath expression xpath=//a[contains(@href,'/property/search/hEC4ocSW0')] because of the following error:
TypeError: Failed to execute 'evaluate' on 'Document': The result is not a node set, and therefore cannot be converted to the desired type.

... означает, что созданная вами стратегия Locator не была действительным локатором.

От вашего попытки кода довольно очевидно, что xpath in:

driver.findElement(By.xpath("xpath=//div[@id='__layout']/div/div[2]/section/div/table/tbody/tr/td")).click();

имеет неправильный формат.


Решение

В соответствии с рекомендациями идеальное выражение xpath должно быть:

driver.findElement(By.xpath("//div[@id='__layout']/div/div[2]/section/div/table/tbody/tr/td")).click();

Вы можете найти подробное обсуждение в InvalidSelectorError: неверный селектор: невозможно найти элемент с выражением xpath

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...