I want to close all the ads that appears in the webpage one by one. The ads can appear in different places, two or one in one row.
I have tryed to write driver.findelement(By.xpath("//div[@id='cbb']")).click()
but the problem is that all the ads have the same code for the close button.
Is there another way to do it?
Option #1
I would suggest using JavascriptExecutor. You can basically add style='visibility: hidden;'
to the HTML block (ad's HTML in your case):
public void hideElement(String xpath)
{
WebElement element = driver.findElement(By.xpath(xpath));
((JavascriptExecutor)driver).executeScript("arguments[0].style.visibility='hidden'", element);
}
For hiding multiple elements, you would need to come up with JS function, that will hide elements and then pass it as string to the executeScript()
public void hideElements()
{
String jscode = "var elements = document.getElementsByClassName('className');
for (var i = 0; i < elements.length; i++){
elements[i].style.display = 'none';
};";
// escaping single / double quotes / tabs / line breaks / so on
jscode = escapeJS(jscode);
((JavascriptExecutor)driver).executeScript(jscode);
}
helper function (needs this import: org.apache.commons.lang3.StringEscapeUtils;
- you can get this library from here):
/**
* Escapes JS.
*/
public static String escapeJS(String value) {
return StringEscapeUtils.escapeEcmaScript(value);
}
NOTE, make sure add necessary timeouts to wait for all ads to be loaded on the page before trying to hide them
Option #2 - a bit hardcore if you don't have jQuery on your page
IF you don't have jQuery - you can add it to DOM (that will require some Java code to be added) and then use its methods to hide elements within Java code that I posted above
IF you have jQuery loaded on your page - just search for jQuery codes to hide HTML on the page (alternative to vanilla JS I posted above) and add those codes to Java function.