Home > Enterprise >  Cannot save my login state in Selenium python
Cannot save my login state in Selenium python

Time:09-30

It seems that Instagram doesn't allow me to Log In in automate tab. Did anyone here face the same problem?

In the past I didn't have any problem but now it seems that Instagram does not allow the user to Log In in a automate tab. The following message shows up:

There was a problem logging you into Instagram. Please try again soon.

As soon as I use a regular tab and "manually" log in, it works. The same problem happens in a private tab.

CodePudding user response:

There are two programs for this task. First one will save the authentication. We have imported pickle which will be used to save the file of our login state. sleep is used to make the refresh rate slower. All you need to do is run the program and login your Instagram. driver.get() will constantly read your login state. I have made sleep(10) so it will be updated every 10 seconds. You can adjust it as you like. After successfully logging in. Make sure you make Instagram remember you. Just wait 10s and then close the browser and selenium working behind but don't close your python program. The program will get an error when it cannot read the state of browser which is handled by our try, except. When error arises, the program will detect our job is done, it will exit loop and save our login state in 'auth.pkl' file.

from selenium import webdriver
from time import sleep
import pickle
driver = webdriver.Chrome()
driver.get("https://www.instagram.com/")
while True:
    sleep(10)
    try:
        state=driver.get_cookies()
    except:
        break
pickle.dump(state,open("auth.pkl","wb"))
print(state)

The second part is just simply loading your "auth.pkl" file and use your Instagram, this program works for other sites login too. Here is our part, we are finding the login state and using it to run Instagram in loaded state.

from selenium import webdriver
import pickle
driver = webdriver.Chrome()

driver.get("https://www.instagram.com/")
cookies = pickle.load(open("auth.pkl", "rb"))
for cookie in cookies:
    driver.add_cookie(cookie)
driver.get("https://www.instagram.com/")
  • Related