Selenion WebDriver Instagram Bot 不喜欢图片

Selenion WebDriver Instagram Bot not liking pictures

我知道最好做一个基于 INSTAGRAM API 的机器人,但我已经制作了一个 selenium firefox 的机器人,几个月前它还在工作,但我知道我想再次 运行 它是不再喜欢图片

   def like_photo(self, hashtag):
        driver = self.driver
        driver.get("https://www.instagram.com/explore/tags/" + hashtag + "/")
        time.sleep(2)

        # gathering photos
        pic_hrefs = []
        for i in range(1, 7):
            try:
                driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
                time.sleep(2)
                # getting hashtags
                hrefs_in_view = driver.find_elements_by_tag_name('a')
                # finding hrefs
                hrefs_in_view = [elem.get_attribute('href') for elem in hrefs_in_view
                                 if '.com/p/' in elem.get_attribute('href')]
                # building list of photos
                [pic_hrefs.append(href) for href in hrefs_in_view if href not in pic_hrefs]
            except Exception:
                continue

        # Liking photos
        unique_photos = len(pic_hrefs)
        for pic_href in pic_hrefs:
            driver.get(pic_href)
            time.sleep(2)
            try:
                time.sleep(random.randint(2, 4))
                like_button = driver.find_element_by_xpath('/html/body/div[4]/div[2]/div/article/div[2]/section[1]/span[1]/button').click()
                # liking photo
                like_button().click()
                time.sleep(random.randint(1, 2))
            except Exception as e:
                time.sleep(2)
            unique_photos -= 1

以上是通过给定主题标签收集照片然后点赞的代码,收集部分工作正常但点赞没有发生。也许这是 XPATH 的问题?这就是我一开始的想法,但如果是这样的话,我应该改用哪一个呢?

如果它之前有效并且您没有更改代码,则可能是因为该站点发生了一些变化

我建议尽可能少使用 xpath 并优先考虑 Id 名称 class...如果它们在某些导航器上没有唯一的,您可以右键单击检查器中的元素并复制xpath

此外,对于您的代码,如果您想全部点赞,只需点击一个即可:

Likes=driver.findElementsById(id)

for x in likes:
    x.click()

代码确实可以正常工作,您应该只更改查找 like_button

的行

而不是:

like_button = driver.find_element_by_xpath('/html/body/div[4]/div[2]/div/article/div[2]/section[1]/span[1]/button').click()

使用这个:like_button = driver.find_element_by_xpath('//*[@aria-label="Like"]').click()