Selenium Python - How to handle a random pop up? Selenium Python - How to handle a random pop up? selenium selenium

Selenium Python - How to handle a random pop up?


I've encountered this on sites that I work on also. What I've found on our site is that it's not really random, it's on a timer. So basically the way it works is a customer comes to the site. If they haven't been prompted to sign up for X, then they get a popup. If they signed up or dismissed the popup, a cookie is written tracking that they already got the message. You want to find that tracking cookie and recreate it to prevent the popups.

What I did was find that cookie, recreate it on an error page on the site domain (some made up page like example.com/some404page), and then start the script as normal. It completely prevents the popup from occurring.

To find out if this is your case, navigate to the home page (or whatever is appropriate) and just wait for the popup. That will give you a sense of how long the timer is. Close the popup and reload the page. If the popup doesn't occur again, then I'm guessing it's the same mechanic.

To find the cookie, clear cookies in your browser and open your site again. (Don't close the popup yet). I use Chrome so I'll describe how to do it. The general approach should work in other browsers but the specific steps and command names may vary.

  1. Open up the devtools (F12)
  2. Navigate to the Application tab and find Cookies (left panel)
  3. Expand Cookies and click on the domain of the site you are working on. There may be a lot of cookies in there from other sites, depending on your site.
  4. Click the Clear All button to clear all the cookies.
  5. Close the popup and watch for cookies to be created. Hopefully you will see one or just a few cookies created.
  6. Note the name of the cookies and delete them one at a time and reload the page and wait the 15s (or whatever) and see if the popup occurs.

Once the popup appears, you know that the last cookie you deleted is the one you need to recreate. You can now write a quick function that creates the cookie using Selenium by navigating to the dummy error page, example.com/some404page, and create the cookie. Call that function at the start of your script. Profit.


I have encountered a similar kind of situation.

My recommendation to you is speak to your front end devs or the company which provides the feedback survey and ask them for a script to disable the pop-ups for a browser session that you run.

Then, execute the script using selenium library(like JavascriptExecutor) as soon as you open the web page so that you do not see the random occuring pop-ups.