Selenim chrome driver 无法定位嵌套的
  • 标签。
  • huangapple go评论81阅读模式
    英文:

    Selenim chrome driver unable to locate nested <li> tags

    问题

    我试图定位无法从`by.xpath`查询中获取的嵌套的`nl`标签。
    
    以下是我在Java中的相关代码行。
    
    driver.findElement(By.xpath("//div[@id='navbarNav']/following-sibling::ul[1]/li[2]")).click();
    `
    
    我想要匹配:
    
    <a class="sub-nav-link style-scope app-shell active" href="#/trend-analysis/tag-search">Trend Analysis
    
    错误:
    
    Exception in thread "main" org.openqa.selenium.NoSuchElementException: 没有此元素:无法定位元素:{"method":"xpath","selector":"//div[@id='navbarNav']/following-sibling::ul[1]"}
      (Session info: headless chrome=85.0.4183.102)
    有关此错误的文档,请访问:http://seleniumhq.org/exceptions/no_such_element.html
    构建信息:版本:'3.14.0',修订版:'aacccce0',时间:'2018-08-02T20:13:22.693Z'
    系统信息:主机:'root',IP:'127.0.1.1',os.name:'Linux',os.arch:'amd64',os.version:'4.15.0-118-generic',java.version:'1.8.0_265'
    驱动程序信息:org.openqa.selenium.chrome.ChromeDriver
    Capabilities {acceptInsecureCerts: false, browserName: chrome, browserVersion: 85.0.4183.102, chrome: {chromedriverVersion: 85.0.4183.87 (cd6713ebf92fa...,userDataDir: /tmp/.com.google.Chrome.qnBVf1},goog:chromeOptions: {debuggerAddress: localhost:35357},javascriptEnabled: true,networkConnectionEnabled: false,pageLoadStrategy: normal,platform: LINUX,platformName: LINUX,proxy: Proxy(),setWindowRect: true,strictFileInteractability: false,timeouts: {implicit: 0,pageLoad: 300000,script: 30000},unhandledPromptBehavior: dismiss and notify,webauthn:virtualAuthenticators: true}
    会话 ID:99a0f9193871a6e94151d885c331875d
    *** 元素信息:{Using=xpath,value=//div[@id='navbarNav']/following-sibling::ul[1]}
            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.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:548)
            at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:322)
            at org.openqa.selenium.remote.RemoteWebDriver.findElementByXPath(RemoteWebDriver.java:424)
            at org.openqa.selenium.By$ByXPath.findElement(By.java:353)
            at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:314)
            at GettingStarted.main(GettingStarted.java:96)
    
    
    相关HTML:
    
    <div class="collapse navbar-collapse style-scope app-shell" id="navbarNav">
                    <ul class="app-nav navbar-nav mr-auto style-scope app-shell">
                        <li class="nav-item style-scope app-shell">
                            <a class="nav-link p-3 px-4 style-scope app-shell" href="/#/dashboard">Dashboard</a>
                        </li>
                        <li class="nav-item style-scope app-shell">
                            <a class="nav-link py-3 px-4 style-scope app-shell active" href="/#/trend-analysis/tag-search">TrendAnalysis</a>
                            <ul class="sub-nav d-flex flex-row flex-nowrap list-unstyled style-scope app-shell">
                                <li class="sub-nav-item style-scope app-shell">
                                    <a class="sub-nav-link style-scope app-shell active" href="#/trend-analysis/tag-search">
                                        Trend Analysis
                                    </a>
                                </li>
                                <li class="sub-nav-item style-scope app-shell">
                                    <a class="sub-nav-link style-scope app-shell" href="#/trend-analysis/value-based-search">
                                        Value-Based Search
                                    </a>
                                </li>
                      .....
    
    我花了整整一周的时间来解决这个问题,但无济于事,请帮忙,谢谢。
    
    我用以下代码测试了一下:
    
    WebDriverWait wait = new WebDriverWait(driver, 30);
    wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//div[@id='navbarNav']/ul")));
    
    driver.findElement(By.xpath("//div[@id='navbarNav']//li/a[contains(@href,'tag-search')]")).click();
    
    更新:
    
    Exception in thread "main" org.openqa.selenium.TimeoutException: 期望的条件失败:等待元素可点击:By.xpath: //div[@id='navbarNav']/ul(尝试了30秒,间隔为500毫秒)
    构建信息:版本:'3.14.0',修订版:'aacccce0',时间:'2018-08-02T20:13:22.693Z'
    系统信息:主机:'root',IP:'127.0.1.1',os.name:'Linux',os.arch:'amd64',os.version:'4.15.0-118-generic',java.version:'1.8.0_265'
    驱动程序信息:org.openqa.selenium.chrome.ChromeDriver
    Capabilities {acceptInsecureCerts: false, browserName: chrome, browserVersion: 85.0.4183.102, chrome: {chromedriverVersion: 85.0.4183.87 (cd6713ebf92fa...,userDataDir: /tmp/.com.google.Chrome.7m6LU4},goog:chromeOptions: {debuggerAddress: localhost:38779},javascriptEnabled: true,networkConnectionEnabled: false,pageLoadStrategy: normal,platform: LINUX,platformName: LINUX,proxy: Proxy(),setWindowRect: true,strictFileInteractability: false,timeouts: {implicit: 0,pageLoad: 300000,script: 30000},unhandledPromptBehavior: dismiss and notify,webauthn:virtualAuthenticators: true}
    会话 ID:6
    
    <details>
    <summary>英文:</summary>
    
    I&#39;m trying to locate nested `nl` tag which I cannot get it from `by.xpath` query.
    
    Here is my relevant line of code in java.
    
        driver.findElement(By.xpath(&quot;//div[@id=&#39;navbarNav&#39;]/following-sibling::ul[1]/li[2]&quot;)).click();
    `
    I want to match:
     
        &lt;a class=&quot;sub-nav-link style-scope app-shell active&quot; href=&quot;#/trend-analysis/tag-search&quot;&gt;Trend Analysis
    
    Error:
    
        Exception in thread &quot;main&quot; org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {&quot;method&quot;:&quot;xpath&quot;,&quot;selector&quot;:&quot;//div[@id=&#39;navbarNav&#39;]/following-sibling::ul[1]&quot;}
          (Session info: headless chrome=85.0.4183.102)
        For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
        Build info: version: &#39;3.14.0&#39;, revision: &#39;aacccce0&#39;, time: &#39;2018-08-02T20:13:22.693Z&#39;
        System info: host: &#39;root&#39;, ip: &#39;127.0.1.1&#39;, os.name: &#39;Linux&#39;, os.arch: &#39;amd64&#39;, os.version: &#39;4.15.0-118-generic&#39;, java.version: &#39;1.8.0_265&#39;
        Driver info: org.openqa.selenium.chrome.ChromeDriver
        Capabilities {acceptInsecureCerts: false, browserName: chrome, browserVersion: 85.0.4183.102, chrome: {chromedriverVersion: 85.0.4183.87 (cd6713ebf92fa..., userDataDir: /tmp/.com.google.Chrome.qnBVf1}, goog:chromeOptions: {debuggerAddress: localhost:35357}, javascriptEnabled: true, networkConnectionEnabled: false, pageLoadStrategy: normal, platform: LINUX, platformName: LINUX, proxy: Proxy(), setWindowRect: true, strictFileInteractability: false, timeouts: {implicit: 0, pageLoad: 300000, script: 30000}, unhandledPromptBehavior: dismiss and notify, webauthn:virtualAuthenticators: true}
        Session ID: 99a0f9193871a6e94151d885c331875d
        *** Element info: {Using=xpath, value=//div[@id=&#39;navbarNav&#39;]/following-sibling::ul[1]}
                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.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:548)
                at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:322)
                at org.openqa.selenium.remote.RemoteWebDriver.findElementByXPath(RemoteWebDriver.java:424)
                at org.openqa.selenium.By$ByXPath.findElement(By.java:353)
                at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:314)
                at GettingStarted.main(GettingStarted.java:96)
    
    
    Relevant HTML:
    
        &lt;div class=&quot;collapse navbar-collapse style-scope app-shell&quot; id=&quot;navbarNav&quot;&gt;
                        &lt;ul class=&quot;app-nav navbar-nav mr-auto style-scope app-shell&quot;&gt;
                            &lt;li class=&quot;nav-item style-scope app-shell&quot;&gt;
                                &lt;a class=&quot;nav-link p-3 px-4 style-scope app-shell&quot; href=&quot;/#/dashboard&quot;&gt;Dashboard&lt;/a&gt;
                            &lt;/li&gt;
                            &lt;li class=&quot;nav-item style-scope app-shell&quot;&gt;
                                &lt;a class=&quot;nav-link py-3 px-4 style-scope app-shell active&quot; href=&quot;/#/trend-analysis/tag-search&quot;&gt;TrendAnalysis&lt;/a&gt;
                                &lt;ul class=&quot;sub-nav d-flex flex-row flex-nowrap list-unstyled style-scope app-shell&quot;&gt;
                                    &lt;li class=&quot;sub-nav-item style-scope app-shell&quot;&gt;
                                        &lt;a class=&quot;sub-nav-link style-scope app-shell active&quot; href=&quot;#/trend-analysis/tag-search&quot;&gt;
                                            Trend Analysis
                                        &lt;/a&gt;
                                    &lt;/li&gt;
                                    &lt;li class=&quot;sub-nav-item style-scope app-shell&quot;&gt;
                                        &lt;a class=&quot;sub-nav-link style-scope app-shell&quot; href=&quot;#/trend-analysis/value-based-search&quot;&gt;
                                            Value-Based Search
                                        &lt;/a&gt;
                                    &lt;/li&gt;
                          .....
    
    I have spend whole week fixing the issue but no avail, kindly help thanks.
    
    I tested the code with 
    
        WebDriverWait wait = new WebDriverWait(driver, 30);
        wait.until(ExpectedConditions.elementToBeClickable(By.xpath(&quot;//div[@id=&#39;navbarNav&#39;]/ul&quot;)));
        
        driver.findElement(By.xpath(&quot;//div[@id=&#39;navbarNav&#39;]//li/a[contains(@href,&#39;tag-search&#39;)]&quot;)).click();
    
    Update:
    
        Exception in thread &quot;main&quot; org.openqa.selenium.TimeoutException: Expected condition failed: waiting for element to be clickable: By.xpath: //div[@id=&#39;navbarNav&#39;]/ul (tried for 30 second(s) with 500 milliseconds interval)
        Build info: version: &#39;3.14.0&#39;, revision: &#39;aacccce0&#39;, time: &#39;2018-08-02T20:13:22.693Z&#39;
        System info: host: &#39;root&#39;, ip: &#39;127.0.1.1&#39;, os.name: &#39;Linux&#39;, os.arch: &#39;amd64&#39;, os.version: &#39;4.15.0-118-generic&#39;, java.version: &#39;1.8.0_265&#39;
        Driver info: org.openqa.selenium.chrome.ChromeDriver
        Capabilities {acceptInsecureCerts: false, browserName: chrome, browserVersion: 85.0.4183.102, chrome: {chromedriverVersion: 85.0.4183.87 (cd6713ebf92fa..., userDataDir: /tmp/.com.google.Chrome.7m6LU4}, goog:chromeOptions: {debuggerAddress: localhost:38779}, javascriptEnabled: true, networkConnectionEnabled: false, pageLoadStrategy: normal, platform: LINUX, platformName: LINUX, proxy: Proxy(), setWindowRect: true, strictFileInteractability: false, timeouts: {implicit: 0, pageLoad: 300000, script: 30000}, unhandledPromptBehavior: dismiss and notify, webauthn:virtualAuthenticators: true}
        Session ID: 6e2d32881f709e2e0d727d8cc45813c4
                at org.openqa.selenium.support.ui.WebDriverWait.timeoutException(WebDriverWait.java:113)
                at org.openqa.selenium.support.ui.FluentWait.until(FluentWait.java:283)
                at GettingStarted.main(GettingStarted.java:103)
    
    
    Update 2:
    
    when i run the code with just:
     
        driver.findElement(By.xpath(&quot;//div[@id=&#39;navbarNav&#39;]//li/a[contains(@href,&#39;tag-search&#39;)]&quot;)).click();
    
    I get:
    
        Exception in thread &quot;main&quot; org.openqa.selenium.ElementNotInteractableException: element not interactable
          (Session info: headless chrome=85.0.4183.102)
    
    
    
    </details>
    
    
    # 答案1
    **得分**: 1
    
    在点击元素之前添加一些等待。
    
    ```java
    String myElement = "(//div[@id='navbarNav']//li/a[contains(@href,'tag-search')])[1]";
    WebDriverWait wait = new WebDriverWait(driver, 30);
    wait.until(ExpectedConditions.elementToBeClickable(By.xpath(myElement)));
    

    或者

    wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(myElement)));
    

    或者

    wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(myElement)));
    

    您还需要使用 xpath 定位到正确的锚元素。

    driver.findElement(By.xpath(myElement)).click();
    
    英文:

    Add some wait before clicking on the element.

    String myElement = &quot;(//div[@id=&#39;navbarNav&#39;]//li/a[contains(@href,&#39;tag-search&#39;)])[1]&quot;;    
    WebDriverWait wait = new WebDriverWait(driver, 30);
    wait.until(ExpectedConditions.elementToBeClickable(By.xpath(myElement)));
    

    or

    wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(myElement)));
    

    or

    wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(myElement)));
    

    You also need to target the correct anchor element using xpath.

    driver.findElement(By.xpath(myElement)).click()
    

    答案2

    得分: 1

    使用Threads.sleep(10)检查,确保带有这个时间元素的内容是否可点击,如果元素不可点击,则您制作的xpath可能有误。

    但如果它是可点击的,那么请同时使用2个等待条件,像这样:

    String myElement = "(//div[@id='navbarNav']//li/a[contains(@href,'tag-search')])[1]";
    WebDriverWait wait = new WebDriverWait(driver, 30);
    wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(myElement)));
    wait.until(ExpectedConditions.elementToBeClickable(By.xpath(myElement)));
    driver.findElement(By.xpath(myElement)).click();
    
    英文:

    Check with Threads.sleep(10), that either with that time element is clickable or not, if element is not clickable it should be the xpath you are making is wrong.

    But If it is clicking, Then Use 2 waits side by side
    Like This:

    String myElement = &quot;(//div[@id=&#39;navbarNav&#39;]//li/a[contains(@href,&#39;tag-search&#39;)])[1]&quot;;    
    WebDriverWait wait = new WebDriverWait(driver, 30);
    wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(myElement)));
    wait.until(ExpectedConditions.elementToBeClickable(By.xpath(myElement)));
    driver.findElement(By.xpath(myElement)).click()
    

    答案3

    得分: 1

    以下是翻译后的内容:

    要通过文本为趋势分析的元素执行click(),您可以使用以下任一定位策略

    • linkText定位策略:

      driver.findElement(By.linkText("Trend Analysis")).click();
      
    • partialLinkText定位策略:

      driver.findElement(By.partialLinkText("Trend Analysis")).click();
      
    • cssSelector定位策略:

      driver.findElement(By.cssSelector("div#navbarNav li.sub-nav-item.style-scope.app-shell>a[href$='tag-search']")).click();
      
    • xpath定位策略:

      driver.findElement(By.xpath("//div[@id='navbarNav']//li[@class='sub-nav-item style-scope app-shell']/a[contains(@href, 'tag-search')][contains(., 'Trend Analysis')]")).click();
      

    理想情况下,要在元素上执行click()操作,您需要使用WebDriverWait来等待elementToBeClickable(),然后您可以使用以下任一定位策略

    • linkText定位策略:

      new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.linkText("Trend Analysis"))).click();
      
    • partialLinkText定位策略:

      new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.partialLinkText("Trend Analysis"))).click();
      
    • cssSelector定位策略:

      new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("div#navbarNav li.sub-nav-item.style-scope.app-shell>a[href$='tag-search']"))).click();
      
    • xpath定位策略:

      new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//div[@id='navbarNav']//li[@class='sub-nav-item style-scope app-shell']/a[contains(@href, 'tag-search')][contains(., 'Trend Analysis')]"))).click();
      
    英文:

    To click() on the element with text as Trend Analysis you can use either of the following Locator Strategies:

    • linkText:

      driver.findElement(By.linkText(&quot;Trend Analysis&quot;)).click();
      
    • partialLinkText:

      driver.findElement(By.partialLinkText(&quot;Trend Analysis&quot;)).click();
      
    • cssSelector:

      driver.findElement(By.cssSelector(&quot;div#navbarNav li.sub-nav-item.style-scope.app-shell&gt;a[href$=&#39;tag-search&#39;]&quot;)).click();
      
    • xpath:

      driver.findElement(By.xpath(&quot;//div[@id=&#39;navbarNav&#39;]//li[@class=&#39;sub-nav-item style-scope app-shell&#39;]/a[contains(@href, &#39;tag-search&#39;)][contains(., &#39;Trend Analysis&#39;)]&quot;)).click();
      

    Ideally, to click() on the element you need to induce WebDriverWait for the elementToBeClickable() and you can use either of the following Locator Strategies:

    • linkText:

      new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.linkText(&quot;Trend Analysis&quot;))).click();
      
    • partialLinkText:

      new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.partialLinkText(&quot;Trend Analysis&quot;))).click();
      
    • cssSelector:

      new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector(&quot;div#navbarNav li.sub-nav-item.style-scope.app-shell&gt;a[href$=&#39;tag-search&#39;]&quot;))).click();
      
    • xpath:

      new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath(&quot;//div[@id=&#39;navbarNav&#39;]//li[@class=&#39;sub-nav-item style-scope app-shell&#39;]/a[contains(@href, &#39;tag-search&#39;)][contains(., &#39;Trend Analysis&#39;)]&quot;))).click();
      

    huangapple
    • 本文由 发表于 2020年9月25日 23:23:32
    • 转载请务必保留本文链接:https://go.coder-hub.com/64067016.html
    匿名

    发表评论

    匿名网友

    :?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

    确定