硒如何通过元素ID查找

时间:2019-01-11 21:49:18

标签: java selenium xpath css-selectors webdriverwait

<button id="attachment-trigger-ember1000" class="msg-form__footer-action button-tertiary-medium-round-muted m0" type="button" style="" xpath="1">
  <span class="visually-hidden">Attach a file</span>
  <li-icon aria-hidden="true" type="paperclip-icon"><svg viewBox="0 0 24 24" width="24px" height="24px" x="0" y="0" preserveAspectRatio="xMinYMin meet" class="artdeco-icon" focusable="false"><path d="M8,6h9.5c3,0,5.5,2.5,5.5,5.5S20.5,17,17.5,17H5c-2.2,0-4-1.8-4-4s1.8-4,4-4h9.5c1.4,0,2.5,1.1,2.5,2.5S15.9,14,14.5,14H8v-2h6.5c0.3,0,0.6-0.1,0.6-0.4c0,0,0,0,0-0.1c0-0.3-0.3-0.5-0.5-0.5c0,0-0.1,0-0.1,0H5c-1-0.1-2,0.6-2.1,1.6c0,0.1,0,0.3,0,0.4c-0.1,1,0.7,1.9,1.7,2c0.1,0,0.3,0,0.4,0h12.6c1.9,0,3.5-1.5,3.5-3.3c0-0.1,0-0.1,0-0.2c0-1.9-1.4-3.4-3.3-3.5c-0.1,0-0.1,0-0.2,0H8V6z" class="large-icon" style="fill: currentColor"></path></svg></li-icon>
</button>

上面是html代码段

我正在尝试使用以下xpath:

driver.findElement(By.xpath("//*[@id=\"attachment-trigger-ember1000\"]")).click();

但它不起作用。

错误消息:

element not found exception

2 个答案:

答案 0 :(得分:4)

您可能想使用By.id代替: https://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/By.html#id-java.lang.String-

driver.findElement(By.id("attachment-trigger-ember1000")).click();

答案 1 :(得分:1)

由于所需元素是启用了Ember.js的元素,因此id属性是 dynamic ,您必须引入 WebDriverWait ,您可以使用以下解决方案:

  • cssSelector

    WebElement myButton = new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("button.msg-form__footer-action.button-tertiary-medium-round-muted.m0[id^='attachment-trigger-ember']")));
    
  • xpath

    WebElement myButton = new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//button[@class='msg-form__footer-action button-tertiary-medium-round-muted m0' and starts-with(@id, 'attachment-trigger-ember')]")));
    
相关问题