I've been struggling with this for a while. I have a button like this.
It sometimes works and sometimes doesn't. I'm confused.
I want to click on this:
It contains this info:
<strong data-bind="css: {'admin__collapsible-title': collapsible,
title: !collapsible,
'_changed': changed,
'_loading': loading,
'_error': error}" >
<span data-bind="i18n: label">Sales Matrix</span>
<!-- ko if: collapsible --><span >
<span >
<span ></span>
<span data-bind="i18n: 'Changes have been made to this section that have not been saved.'">Changes have been made to this section that have not been saved.</span>
</span>
<span >
<span ></span>
<span data-bind="i18n: 'This tab contains invalid data. Please resolve this before saving.'">This tab contains invalid data. Please resolve this before saving.</span>
</span>
<span >
<span >
<!-- ko repeat: 8 --><span data-repeat-index="0"></span><span data-repeat-index="1"></span><span data-repeat-index="2"></span><span data-repeat-index="3"></span><span data-repeat-index="4"></span><span data-repeat-index="5"></span><span data-repeat-index="6"></span><span data-repeat-index="7"></span><!-- /ko -->
</span>
</span>
</span><!-- /ko -->
</strong>
The XPATH is:
//*[@id="container"]/div/div[2]/div[4]/div[1]/strong
I have tried many ways to click on that button but nothing seems to be working for me.
I tried:
a) driver.findElement(By.xpath("//span[contains(text(),'Sales Matrix')]")).click();.
b) driver.findElement(By.xpath("//span[normalize-space()='Sales Matrix']")).click();.
c) WebElement drf=driver.findElement(By.xpath("//div[@label='Sales Matrix']"));
Thread.sleep(1000);
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", drf);
I even use the JAVASCRIPTEXECUTOR technique but the behaviour is strange.
What should i do?
CodePudding user response:
If there's a span
ancestor above the strong
element, it might throw off your click. Try this selector:
"//strong//span[contains(., 'Sales Matrix')]"
driver.findElement(By.xpath("//strong//span[contains(., 'Sales Matrix')]")).click();
And if that wasn't the case, you probably need to wait longer before finding the element. That's where WebDriverWait
comes into play.
CodePudding user response:
I guess you are missing a delay. Element should be clicked only when it is clickable.
The best way to do that is to use WebDriverWait
.
Please try this:
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//span[contains(.,'Sales Matrix')]"))).click();