【问题标题】:How to locate Element via CSS Selector/XPath?如何通过 CSS 选择器/XPath 定位元素?
【发布时间】:2014-02-12 15:53:24
【问题描述】:
<a class="LinkDetail" href="/settings/carsettings?xyz=L_11:1:*:2&carid=199&carnumber=4294967295" target="_top" tabindex="23"/>

在上面的链接中,我需要使用/settings/carsettingscarid=199定位元素

使用 CSS 定位器。任何人都可以让我知道相同的语法吗?也分享 XPath 的语法。

【问题讨论】:

    标签: selenium xpath selenium-webdriver css-selectors


    【解决方案1】:

    请向我们展示您的尝试,以便我们分析您未能实现的目标。如果以下 CSS 选择器/XPath 不起作用,请发布您的堆栈跟踪和更多 HTML 代码以找到最佳定位器。

    CSS 选择器

    a[href*='settings/carsettings'][href*='carid=199']
    

    XPath

    .//a[contains(@href, 'settings/carsettings') and contains(@href, 'carid=199')]
    

    【讨论】:

      【解决方案2】:

      您需要的可以使用以下代码实现:-

      //get all <a> tags in the webpage to a list
      List<WebElements> aTags = driver.findElements(By.tagName("a"));
      
      
      int index = 0; 
      //iterate through list of <a> tags
      for (WebElement aTag: aTags) {
          //get the href attribute of each <a> tag
          String href = aTag.getAttribute("href");
      
          //see if the href contains /settings/carsettings and carid=199
          if (href.contains("/settings/carsettings")&&href.contains("carid=199")) {
              //if it contains break out of for loop. This esssentially gives the index
              break;
          }
          index++;
      }
      
      //get the required <a> tag using the index
      WebElement required = aTags.get(index);
      

      如果这对你有帮助,请告诉我。

      【讨论】:

        猜你喜欢
        • 2019-12-25
        • 2019-07-20
        • 2021-08-21
        • 2021-04-15
        • 2021-11-15
        • 1970-01-01
        • 2021-11-21
        • 1970-01-01
        • 2015-09-08
        相关资源
        最近更新 更多