首页 > 解决方案 > Selenium 单击非按钮元素

问题描述

所以我试图点击一个不是按钮元素的元素,html代码如下:

<div class="menu-item-header">
   <span class="header-title"><span class="icon-wrapper"><i class="icon-helper"></i></span>Help
   </span> <!--When a client clicks this it redirects them to the appropriate place (this is a React website)-->
</div>

原始网站看起来像这样:

<div class="menu-item-header">
   <span class="header-title"><span class="icon-wrapper"><i class="icon-helper"></i></span>Help
   </span> <!---->
</div>
<div class="menu-item-header">
   <span class="header-title"><span class="icon-wrapper"><i class="icon-helper2"></i></span>Help2
   </span> <!---->
</div>
...

我尝试了以下方法来单击元素:

WebElement element = browser.findElement(...);
element.click();

然而这并没有奏效。

标签: javaseleniumselenium-webdriverxpathwebdriverwait

解决方案


所需的元素是一个React元素,因此要单击带有文本作为帮助的元素,您需要诱导WebDriverWait并且elementToBeClickable()您可以使用以下基于定位器策略之一:

new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//div[@class='menu-item-header']/span[@class='header-title' and contains(., 'Help')]"))).click();

推荐阅读