I am trying to make a program that detects ads and then removes them. This is my code so far:
from selenium import webdriver
url = input('Enter URL to detect ads from: ')
browser = webdriver.Chrome()
browser.get('http://'+url)
all_iframes = browser.find_elements_by_tag_name("iframe")
print(' ')
for iframe in all_iframes:
browser.switch_to.frame(iframe)
print("Ad Found")
browser.switch_to.default_content()
print(' ')
print('Total Ads: ' + str(len(all_iframes)))
My question is that is there a way to remove/hide these ads my program has detected?
You can simply set hidden
attribute to each iframe
to make them invisible as follow:
from selenium import webdriver
url = input('Enter URL to detect ads from: ')
browser = webdriver.Chrome()
browser.get('http://'+url)
all_iframes = browser.find_elements_by_tag_name("iframe")
if len(all_iframes) > 0:
print("Ad Found\n")
browser.execute_script("""
var elems = document.getElementsByTagName("iframe");
for(var i = 0, max = elems.length; i < max; i++)
{
elems[i].hidden=true;
}
""")
print('Total Ads: ' + str(len(all_iframes)))
else:
print('No frames found')
P.S. Note that not every iframe
on page is an advertisement!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With