8

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?

1 Answer 1

13

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!

Sign up to request clarification or add additional context in comments.

5 Comments

thanks for your reply. Can you tell me where exactly i should put the code you answered?
Is there a way to find all ads on a page using ad servers on this link: link or is there any way of finding all ads on a page?
Do you want to check hypertext reference of each iframe element's embedded link and compare its origin with each of adserver IP? Also I'm not sure that there is a way to determine whether it's an ad on iframe or not. There could be attributes like title="3rd party ad content" or name="google_ads_frame3", but it's not a strong rule... I think you might need to open new ticket to get this info
thanks a lot for your help I will make a new ticket soon
You can mark this answer as Accepted if it solved your current issue

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.