This is the code of web scraping Instagram using Selenium with Python:
def direct_message(self, usernames, message): try: # Open Direct Message section dm_btn = WebDriverWait(self.driver, 10).until( EC.element_to_be_clickable((By.XPATH, "//a[@aria-label='Direct messaging - 0 new notifications link']//div//div[@class='x9f619 xxk0z11 xii2z7h x11xpdln x19c4wfv xvy4d1p']//*[name()='svg']")) ) dm_btn.click() except Exception as e: print(f"Direct Message button not found: {e}") return # Stop execution if the DM button is not found sleep(5) click_search_dm = self.driver.find_element(By.XPATH, "//div[contains(text(),'Send message')]") click_search_dm.click() sleep(5) try: # Find the search input field search_dm = WebDriverWait(self.driver, 10).until( EC.element_to_be_clickable((By.XPATH, '/html/body/div[6]/div[1]/div/div[2]/div/div/div/div/div/div/div[1]/div/div[2]/div/div[2]/input')) ) # Send messages to profiles for username in usernames: search_dm.clear() # Clear the search input field search_dm.send_keys(username) sleep(2) try: # Wait for the search results to load and click on the profile profile_click = WebDriverWait(self.driver, 10).until( EC.element_to_be_clickable((By.XPATH, "//div[@role='presentation'][1]//a")) ) profile_click.click() except Exception as e: print(f"Error occurred while clicking on the profile: {e}") continue # Continue to the next iteration if clicking on the profile fails send_msg = self.driver.find_element(By.XPATH, "//div[contains(text(),'Send message')]") send_msg.click() sleep(5) type_msg = self.driver.find_element(By.XPATH, "//textarea") type_msg.send_keys(message) sleep(5) sending_text = self.driver.find_element(By.XPATH, "//button[contains(text(),'Send')]") sending_text.click() sleep(5) except Exception as e: print(f"Error occurred while searching DM: {e}")
The code describes the DM section which is direct message for web scraping in Instagram. What I have done up to now is I have integrated Google sheet API and credentials from the sheet the username can be fetched and the search DM works but it works fine one only one user but if I tried to multiple user after finishing one DM the other gets interrupted.