硒单击非按钮元素

时间:2020-07-14 16:00:40

标签: java selenium selenium-webdriver xpath webdriverwait

因此,我尝试单击不是按钮元素的元素,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();

但是那没用。

2 个答案:

答案 0 :(得分:1)

所需元素是React元素,因此要单击文本为 Help 的元素,您需要为elementToBeClickable()引入WebDriverWait,然后可以使用以下基于Locator Strategy之一:

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

答案 1 :(得分:0)

您始终可以默认使用JavaScript。

driver.execute_script("document.getElementById('#<id>').click()");

或者,如果仅具有类标识符:

driver.execute_script("document.getElementsByClassName('.<classname>')[0].click()")

话虽这么说,使用span或divs作为功能按钮不符合可访问性标准,所以如果您可以访问代码库或可以影响代码库,我强烈建议您使用按钮代替。