0

I was trying to remove the ad and other pop-up using selenium after opening the webpage. The pop-up is getting removed but the ad is not getting removed. There is some error in executing javascript code(using it remove ad). For which there is no reason given. Also, for the ad, when I open the webpage myself by typing the link then ad does not appear but when I run the program, in code generated browser ad appears(reason I don't know). I have attached both code and error. Here is the code

from selenium import webdriver
import time
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()
driver.get("http://indianexpress.com/columnists/")

// To remove pop-up
later = driver.find_elements(By.CLASS_NAME, "iz_block_button")
later[0].click()

//to remove ad
all_iframes = driver.find_elements_by_tag_name("iframe")
if len(all_iframes) > 0:
    print("Ad Found\n")
    driver.execute_script("""
    var elems = document.getElementsByTagName('iframe'); 
    for(var i = 0, max = elems.length; i < max; i++)
    { 
        elems[i].visibility=hidden; 
    } 
                         """)
    print('Total Ads: ' + str(len(all_iframes)))
else:
    print('No frames found')

driver.close()

Error:-

Traceback (most recent call last):
  File "/Users/arjungoyal/Desktop/untitled/a.py", line 23, in <module>
    """)
  File "/usr/local/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 627, in execute_script
    'args': converted_args})['value']
  File "/usr/local/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 312, in execute
    self.error_handler.check_response(response)
  File "/usr/local/lib/python3.6/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: unknown error: hidden is not defined
  (Session info: chrome=66.0.3359.181)
  (Driver info: chromedriver=2.38.552518 (183d19265345f54ce39cbb94cf81ba5f15905011),platform=Mac OS X 10.13.4 x86_64)

Selenium version - 3.11.0 Please, someone, tell what the error is and how to remove it.

1

The problem is that your Javascript is treating hidden as a variable because it's not enclosed in quotes.

Since Javascript can be pretty relaxed about whether you use single or double quotes, you have two options here:

Use single-quotes so you don't break the string:

elems[i].visibility='hidden';

Escape the double quotes so that they're treated as literals by your python code.

elems[i].visibility=\"hidden\";

Either method should work for you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.