【问题标题】:Selenion WebDriver Instagram Bot not liking picturesSelenion WebDriver Instagram Bot 不喜欢图片
【发布时间】:2020-04-25 10:19:07
【问题描述】:

我知道做一个基于 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 的问题?这就是我最初的想法,但如果是这种情况,我应该使用哪个?

【问题讨论】:

    标签: python selenium selenium-webdriver bots instagram-api


    【解决方案1】:

    代码确实可以正常工作,您应该只更改查找 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()

    【讨论】:

      【解决方案2】:

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

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

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

      Likes=driver.findElementsById(id)
      
      for x in likes:
          x.click()
      

      【讨论】:

      • 我通过右键单击复制了 Xpath,但不起作用,我使用类名“按钮”并自动跟随主题标签中的每个人,所以其余代码工作我只需要知道如何正确获得赞按钮@rafalou38
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多