Selenium XPATH前兄弟不工作

时间:2018-05-16 02:49:52

标签: java selenium selenium-webdriver xpath

<div class=”ag-cell-label-container ag-header-cell-sorted-none” role=”presentation”
  <span ref=”eMENU” class=”ag-header-icon ag-header-cell-menu-button” aria-hidden=”true” style=”transition:opacity 0.2s;>
    <span class=”ag-icon ag-icon-menu”></span>
  </span>
  <div ref=”eLabel” class=”ag-header-cell-label” role=”presentation”>
    <span ref=”eText” class=”ag-header-cell-text role=”columnheader”> Product</span>

我需要点击我的应用程序中的ag-icon ag-icon menu列产品。 我写了下面的xpath来做同样的事情。但是有超过1个元素匹配兄弟中给出的xpath,这就是为什么我将事件硬编码为[1]。有没有办法点击ag-icon ag-icon menu而不使用引用?

WebElement pipeline = driver.findElement(By.xpath("//span[text()='Product']"));
WebElement parent = pipeline.findElement(By.xpath(".."));
WebElement sibling = parent.findElement(By.xpath("(//preceding-sibling::span[@class='g-header-icon ag-header-cell-menu-button']/span)[1]"));
sibling.click();

2 个答案:

答案 0 :(得分:0)

// Option 1
String xpath = "//div[div/span[@role='columnheader' and text()='Product']" + 
"//span[contains(@class, 'ag-icon-menu')]"

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


// Option 2
String xpath = "//div[div/span[@role='columnheader' and text()='Product']"
driver.findElement(By.xpath(xpath))
      .findElement(By.cssSelector("span.ag-icon-menu"))
      .click()

答案 1 :(得分:0)

请尝试使用以下xpath,它将起作用

driver.findElement(By.xpath("//span[contains(@class,'ag-icon') and contains(@class,'ag-icon-menu')]")).click();

当class属性有多个唯一值时,我们可以使用“AND”条件