Search code examples
pythonseleniumwebdriverinstagram

Python Selenium Webdriver - Handling mouseover on Instagram


I'm creating an Instagram Unfollow Tool. The code usually works, but occasionally Instagram will show the information of some user (as if I hovered over that user) and cause my code to stop running because it obscures the buttons that I need to click in order to unfollow a user.

It's easier to understand with an example:

enter image description here

How can I edit my code to make the mouseover information go away (is there a way to turn off these mouseover effects)?

My code:

for i in range(num_following):
    following = self.browser.find_element_by_xpath("/html/body/div[5]/div/div/div[2]/ul/div/li[{}]/div/div[1]/div[2]/div[1]/span/a".format(i))
    following_username = following.get_attribute("title")   
    
    if following_username not in followers:
        # Unfollow account
        following_user_button = self.browser.find_element_by_xpath("/html/body/div[5]/div/div/div[2]/ul/div/li[{}]/div/div[2]/button".format(i))
        following_user_button.click()

        unfollow_user_button = self.browser.find_element_by_xpath("/html/body/div[6]/div/div/div/div[3]/button[1]")
        unfollow_user_button.click()

        print("You've unfollowed {}.".format(following_username))

The error I get:

selenium.common.exceptions.ElementClickInterceptedException: Message: Element is not clickable at point (781,461) because another element obscures it


Solution

  • It seems like the element unfollow_user_button = self.browser.find_element_by_xpath("/html/body/div[6]/div/div/div/div[3]/button[1]") you want to execute .click() on is blocked by a temporary or permanent overlay.

    In such cases you either can wait with ExplicitWait and ExplicitConditions till said blocking element has vanished - though this shouldn't work in this specific case as to my knowledge the popup remains if nothing is done. Another approach is to send the click directly to the element by using the JavascriptExecutor:

    #Find the element - by_xpath or alike
    unfollow_user_button = driver.find_element_by_xpath("XPATH")
    
    #Sending the click via JavascriptExecutor
    driver.execute_script("arguments[0].click();", unfollow_user_button)
    

    Note two things:

    1. driver must obviously be an instance of WebDriver.

    2. I would suggest not using the absolute XPath in general. Going with the relative XPath is less prone to be broken by small changes in the site structure. Click here for a small guide to read through.