【问题标题】:Selenium how to find by element idSelenium 如何通过元素 id 查找
【发布时间】:2019-01-11 21:49:17
【问题描述】:
<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代码sn-p

我正在尝试使用以下 xpath:

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

但它不起作用。

错误信息:

element not found exception

【问题讨论】:

  • “它不起作用”是什么意思?请使用相关的错误消息更新您的问题。

标签: java selenium xpath css-selectors webdriverwait


【解决方案1】:

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

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

【讨论】:

  • 执行该代码时,您确定该元素在页面上吗?在 Selenium/WebDriver 中,您正在等待一些 JavaScript 代码在元素进入页面之前执行,这是一个非常常见的问题。您可能需要等待:toolsqa.com/selenium-webdriver/wait-commands
【解决方案2】:

由于所需元素是启用了Ember.js 的元素,id 属性是动态的,您必须诱导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')]")));
    

【讨论】:

  • 为什么这不起作用,WebElement attachment = new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//button[@class='msg-form__footer-action button -tertiary-medium-round-muted m0' 和 @id='attachment-trigger-ember3920']")));
  • @klobin 正如我在回答中提到的 numeric 部分,即 value 中的 1000 id 属性是动态的。所以每次访问HTML时,动态部分都会变成10003920等,所以我们在构造Locator Strategies时可以不考虑这部分。跨度>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-11-25
  • 1970-01-01
  • 2016-03-12
  • 2017-08-08
  • 1970-01-01
  • 2019-08-16
  • 2015-04-18
相关资源
最近更新 更多