Home > database >  Block advertisements on Selenium
Block advertisements on Selenium

Time:11-06

I'm currently using Selenium for one of my academic assignments regarding quality assurance automation. For this, I'm using a website that is not handled by me or anyone I know.

I have noticed that when I run my test cases, sometimes, advertisements appear on the website in the Chrome window that opens up. Since it is not a pop-up, using disable-popup-blocking does not work. Moreover, since the advertisement doesn't always appear, using a code segment to close the advertisement modal doesn't work either.

The following image depicts an example scenario. enter image description here

Is there a workaround for this issue? Thank you in advance!

@Test
@Order(2)
public void CovertLang() throws InterruptedException {
    // Navigating to 123apps.com website
    driver.get("https://123apps.com/");

    WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));

    // Accessing the language modal
    WebElement langButton = driver.findElement(By.id("language-link"));
    langButton.click();

    // Wait until the modal opens
    wait.until(ExpectedConditions
            .visibilityOfElementLocated(By.className("modal-title")));

    // Selecting German as the language
    WebElement deutschButton = driver.findElement(By.xpath("//a[@href='/de/']"));
    deutschButton.click();

    Thread.sleep(1000);

    // Comparing the web URL
    String newURL = driver.getCurrentUrl();
    assertEquals("https://123apps.com/de/", newURL);
}

The above shows an example of a test I conducted.

CodePudding user response:

You can disable that ad using the below js code:

// Selecting German as the language
WebElement deutschButton = driver.findElement(By.xpath("//a[@href='/de/']"));
deutschButton.click();

Thread.sleep(1000);

JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("const elements = document.getElementsByClassName('adsbygoogle adsbygoogle-noablate'); while (elements.length > 0) elements[0].remove()");

deutschButton.click();

// Comparing the web URL
String newURL = driver.getCurrentUrl();
assertEquals("https://123apps.com/de/", newURL);
  • Related