This is the code to the bot that I have built trying to use selenium eventhough I have been trying to use an xpath or to use the labels or the current dynamic html structure of the instagram it just keeps timing out. Is there anything I can change ?
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import NoSuchElementException, TimeoutException
import time
service = Service('C:\web-drivers\chromedriver.exe')
driver = webdriver.Chrome(service=service)
def login_to_instagram(driver, username, password):
driver.get('https://www.instagram.com/accounts/login/')
time.sleep(5)
username_input = driver.find_element(By.NAME, 'username')
password_input = driver.find_element(By.NAME, 'password')
username_input.send_keys(username)
password_input.send_keys(password)
password_input.send_keys(Keys.RETURN)
time.sleep(5)
def navigate_to_post_and_like(driver, post_url):
driver.get(post_url)
time.sleep(5)
try:
like_button = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.XPATH, '//article//section/span/button/div/span/*[name()="svg"][@aria-label="Like"]'))
)
like_button.click()
print("Post liked")
except (NoSuchElementException, TimeoutException):
print("Failed to find the like button, trying alternative methods.")
try:
heart_svg = driver.find_element(By.XPATH, '//article//section/span/button/div/span/*[name()="svg"]')
if 'Like' in heart_svg.get_attribute('aria-label'):
heart_svg.click()
print("Post liked using alternative method")
except NoSuchElementException:
print("Still failed to find the like button.")
try:
login_to_instagram(driver, 'username', 'password')
navigate_to_post_and_like(driver, 'https://www.instagram.com/p/C7doGQxPqa9/')
finally:
driver.quit()
I tried copying the xpath and add an action to like the post but it just doesnt work, it times out:
//*[@id="mount_0_0_K+"]/div/div/div[2]/div/div/div[1]/section/main/div/div[1]/article/div/div[2]/div/div[2]/section[1]/span[1]/div
loosery composer is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.