Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide/Remove ads with selenium python

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?

like image 721
Vagif Avatar asked Jan 04 '17 09:01

Vagif


1 Answers

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!

like image 117
Andersson Avatar answered Sep 18 '22 12:09

Andersson