Я реализовал функцию, которой нравится вся картинка со страницы Instagram. Его можно использовать на странице «Обзор» или просто на профильной странице пользователя.
Вот как я это сделал.
Сначала, чтобы перейти на страницу профиля с главной страницы Instagram, я создаю xPath для «SearchBox» и xPath для элемента в выпадающем меню, результаты которого соответствуют индексу.
def search(self, keyword, index):
""" Method that searches for a username and navigates to nth profile in the results where n corresponds to the index"""
search_input = "//input[@placeholder=\"Search\"]"
navigate_to = "(//div[@class=\"fuqBx\"]//descendant::a)[" + str(index) + "]"
try:
self.driver.find_element_by_xpath(search_input).send_keys(keyword)
self.driver.find_element_by_xpath(navigate_to).click()
print("Successfully searched for: " + keyword)
except NoSuchElementException:
print("Search failed")
Потом открываю первую картинку:
def open_first_picture(self):
""" Method that opens the first picture on an Instagram profile page """
try:
self.driver.find_element_by_xpath("(//div[@class=\"eLAPa\"]//parent::a)[1]").click()
except NoSuchElementException:
print("Profile has no picture")
Как и каждый из них:
def like_all_pictures(self):
""" Method that likes every picture on an Instagram page."""
# Open the first picture
self.open_first_picture()
# Create has_picture variable to keep track
has_picture = True
while has_picture:
self.like()
# Updating value of has_picture
has_picture = self.has_next_picture()
# Closing the picture pop up after having liked the last picture
try:
self.driver.find_element_by_xpath("//button[@class=\"ckWGn\"]").click()
print("Liked all pictures of " + self.driver.current_url)
except:
# If driver fails to find the close button, it will navigate back to the main page
print("Couldn't close the picture, navigating back to Instagram's main page.")
self.driver.get("https://www.instagram.com/")
def like(self):
"""Method that finds all the like buttons and clicks on each one of them, if they are not already clicked (liked)."""
unliked = self.driver.find_elements_by_xpath("//span[@class=\"glyphsSpriteHeart__outline__24__grey_9 u-__7\" and @aria-label=\"Like\"]//parent::button")
liked = self.driver.find_elements_by_xpath("//span[@class=\"glyphsSpriteHeart__filled__24__red_5 u-__7\" and @aria-label=\"Unlike\"]")
# If there are like buttons
if liked:
print("Picture has already been liked")
elif unliked:
try:
for button in unliked:
button.click()
except StaleElementReferenceException: # We face this stale element reference exception when the element we are interacting is destroyed and then recreated again. When this happens the reference of the element in the DOM becomes stale. Hence we are not able to get the reference to the element.
print("Failed to like picture: Element is no longer attached to the DOM")
Этот метод проверяет, есть ли на картинке кнопка «Далее» для следующей картинки:
def has_next_picture(self):
""" Helper method that finds if pictures has button \"Next\" to navigate to the next picture. If it does, it will navigate to the next picture."""
next_button = "//a[text()=\"Next\"]"
try:
self.driver.find_element_by_xpath(next_button).click()
return True
except NoSuchElementException:
print("User has no more pictures")
return False
Если вы хотите узнать больше, не стесняйтесь взглянуть на мой репозиторий Github: https://github.com/mlej8/InstagramBot