Попробуйте следующие варианты:
# the script is too quick and tries to locate the element before the page is fully loaded. That's why it is useful to use `WebDriverWait`
like = WebDriverWait(driver, 5).until(EC.presence_of_element_located((By.CSS_SELECTOR, '.Szr5J.coreSpriteHeartOpen')))
или
import time
time.sleep(5) # pause 5 sec after login in istagram
like = driver.find_element_by_css_selector('.Szr5J.coreSpriteHeartOpen')
PS Если я правильно понимаю, вы хотите найти все «сердца» на странице. Поэтому вы должны использовать driver.find_elements_by_css_selector
так:
# gives an array of elements found
like = driver.find_elements_by_css_selector('.Szr5J.coreSpriteHeartOpen')
тогда вы можете перебирать эти элементы, используя цикл.
Полный рабочий код здесь:
username = "----"
password = "----" #values present in original file
getdriver = ("https://www.instagram.com/accounts/login/")
driver = webdriver.Chrome(r'C:\testDir\chromedriver_win32\chromedriver.exe')
driver.get(getdriver)
driver.find_element_by_xpath("//input[@name='username']").send_keys(username)
driver.find_element_by_xpath("//input[@name='password']").send_keys(password)
driver.find_element_by_xpath("//button[contains(.,'Log in')]").click()
# after login there is a popup which should be closed
popup = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, '//div/div/button[contains(., Close)]')))
driver.find_element_by_xpath("//div/div/button[contains(., Close)]").click()
WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR, '.Szr5J.coreSpriteHeartOpen')))
# find all 'hearts' presented on the page
likes = driver.find_elements(By.CSS_SELECTOR, ".Szr5J.coreSpriteHeartOpen")
print(len(likes))
print("WORKS")
for x in range(0,len(likes)):
if likes[x].is_displayed():
likes[x].click()
print(x)
Выход:
3
WORKS
0
1
2